001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.net;
018
019import static com.google.common.base.CharMatcher.ASCII;
020import static com.google.common.base.CharMatcher.JAVA_ISO_CONTROL;
021import static com.google.common.base.Charsets.UTF_8;
022import static com.google.common.base.Preconditions.checkArgument;
023import static com.google.common.base.Preconditions.checkNotNull;
024import static com.google.common.base.Preconditions.checkState;
025
026import com.google.common.annotations.Beta;
027import com.google.common.annotations.GwtCompatible;
028import com.google.common.base.Ascii;
029import com.google.common.base.CharMatcher;
030import com.google.common.base.Function;
031import com.google.common.base.Joiner;
032import com.google.common.base.Joiner.MapJoiner;
033import com.google.common.base.MoreObjects;
034import com.google.common.base.Objects;
035import com.google.common.base.Optional;
036import com.google.common.collect.ImmutableListMultimap;
037import com.google.common.collect.ImmutableMultiset;
038import com.google.common.collect.ImmutableSet;
039import com.google.common.collect.Iterables;
040import com.google.common.collect.Maps;
041import com.google.common.collect.Multimap;
042import com.google.common.collect.Multimaps;
043
044import java.nio.charset.Charset;
045import java.nio.charset.IllegalCharsetNameException;
046import java.nio.charset.UnsupportedCharsetException;
047import java.util.Collection;
048import java.util.Map;
049import java.util.Map.Entry;
050
051import javax.annotation.Nullable;
052import javax.annotation.concurrent.Immutable;
053
054/**
055 * Represents an <a href="http://en.wikipedia.org/wiki/Internet_media_type">Internet Media Type</a>
056 * (also known as a MIME Type or Content Type). This class also supports the concept of media ranges
057 * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">defined by HTTP/1.1</a>.
058 * As such, the {@code *} character is treated as a wildcard and is used to represent any acceptable
059 * type or subtype value. A media type may not have wildcard type with a declared subtype. The
060 * {@code *} character has no special meaning as part of a parameter. All values for type, subtype,
061 * parameter attributes or parameter values must be valid according to RFCs
062 * <a href="http://www.ietf.org/rfc/rfc2045.txt">2045</a> and
063 * <a href="http://www.ietf.org/rfc/rfc2046.txt">2046</a>.
064 *
065 * <p>All portions of the media type that are case-insensitive (type, subtype, parameter attributes)
066 * are normalized to lowercase. The value of the {@code charset} parameter is normalized to
067 * lowercase, but all others are left as-is.
068 *
069 * <p>Note that this specifically does <strong>not</strong> represent the value of the MIME
070 * {@code Content-Type} header and as such has no support for header-specific considerations such as
071 * line folding and comments.
072 *
073 * <p>For media types that take a charset the predefined constants default to UTF-8 and have a
074 * "_UTF_8" suffix. To get a version without a character set, use {@link #withoutParameters}.
075 *
076 * @since 12.0
077 *
078 * @author Gregory Kick
079 */
080@Beta
081@GwtCompatible
082@Immutable
083public final class MediaType {
084  private static final String CHARSET_ATTRIBUTE = "charset";
085  private static final ImmutableListMultimap<String, String> UTF_8_CONSTANT_PARAMETERS =
086      ImmutableListMultimap.of(CHARSET_ATTRIBUTE, Ascii.toLowerCase(UTF_8.name()));
087
088  /** Matcher for type, subtype and attributes. */
089  private static final CharMatcher TOKEN_MATCHER = ASCII.and(JAVA_ISO_CONTROL.negate())
090      .and(CharMatcher.isNot(' '))
091      .and(CharMatcher.noneOf("()<>@,;:\\\"/[]?="));
092  private static final CharMatcher QUOTED_TEXT_MATCHER = ASCII
093      .and(CharMatcher.noneOf("\"\\\r"));
094  /*
095   * This matches the same characters as linear-white-space from RFC 822, but we make no effort to
096   * enforce any particular rules with regards to line folding as stated in the class docs.
097   */
098  private static final CharMatcher LINEAR_WHITE_SPACE = CharMatcher.anyOf(" \t\r\n");
099
100  // TODO(gak): make these public?
101  private static final String APPLICATION_TYPE = "application";
102  private static final String AUDIO_TYPE = "audio";
103  private static final String IMAGE_TYPE = "image";
104  private static final String TEXT_TYPE = "text";
105  private static final String VIDEO_TYPE = "video";
106
107  private static final String WILDCARD = "*";
108
109  private static final Map<MediaType, MediaType> KNOWN_TYPES = Maps.newHashMap();
110
111  private static MediaType createConstant(String type, String subtype) {
112    return addKnownType(new MediaType(type, subtype, ImmutableListMultimap.<String, String>of()));
113  }
114
115  private static MediaType createConstantUtf8(String type, String subtype) {
116    return addKnownType(new MediaType(type, subtype, UTF_8_CONSTANT_PARAMETERS));
117  }
118
119  private static MediaType addKnownType(MediaType mediaType) {
120    KNOWN_TYPES.put(mediaType, mediaType);
121    return mediaType;
122  }
123
124  /*
125   * The following constants are grouped by their type and ordered alphabetically by the constant
126   * name within that type. The constant name should be a sensible identifier that is closest to the
127   * "common name" of the media.  This is often, but not necessarily the same as the subtype.
128   *
129   * Be sure to declare all constants with the type and subtype in all lowercase. For types that
130   * take a charset (e.g. all text/* types), default to UTF-8 and suffix the constant name with
131   * "_UTF_8".
132   */
133
134  public static final MediaType ANY_TYPE = createConstant(WILDCARD, WILDCARD);
135  public static final MediaType ANY_TEXT_TYPE = createConstant(TEXT_TYPE, WILDCARD);
136  public static final MediaType ANY_IMAGE_TYPE = createConstant(IMAGE_TYPE, WILDCARD);
137  public static final MediaType ANY_AUDIO_TYPE = createConstant(AUDIO_TYPE, WILDCARD);
138  public static final MediaType ANY_VIDEO_TYPE = createConstant(VIDEO_TYPE, WILDCARD);
139  public static final MediaType ANY_APPLICATION_TYPE = createConstant(APPLICATION_TYPE, WILDCARD);
140
141  /* text types */
142  public static final MediaType CACHE_MANIFEST_UTF_8 =
143      createConstantUtf8(TEXT_TYPE, "cache-manifest");
144  public static final MediaType CSS_UTF_8 = createConstantUtf8(TEXT_TYPE, "css");
145  public static final MediaType CSV_UTF_8 = createConstantUtf8(TEXT_TYPE, "csv");
146  public static final MediaType HTML_UTF_8 = createConstantUtf8(TEXT_TYPE, "html");
147  public static final MediaType I_CALENDAR_UTF_8 = createConstantUtf8(TEXT_TYPE, "calendar");
148  public static final MediaType PLAIN_TEXT_UTF_8 = createConstantUtf8(TEXT_TYPE, "plain");
149  /**
150   * <a href="http://www.rfc-editor.org/rfc/rfc4329.txt">RFC 4329</a> declares
151   * {@link #JAVASCRIPT_UTF_8 application/javascript} to be the correct media type for JavaScript,
152   * but this may be necessary in certain situations for compatibility.
153   */
154  public static final MediaType TEXT_JAVASCRIPT_UTF_8 = createConstantUtf8(TEXT_TYPE, "javascript");
155  /**
156   * <a href="http://www.iana.org/assignments/media-types/text/tab-separated-values">
157   * Tab separated values</a>.
158   *
159   * @since 15.0
160   */
161  public static final MediaType TSV_UTF_8 = createConstantUtf8(TEXT_TYPE, "tab-separated-values");
162  public static final MediaType VCARD_UTF_8 = createConstantUtf8(TEXT_TYPE, "vcard");
163  public static final MediaType WML_UTF_8 = createConstantUtf8(TEXT_TYPE, "vnd.wap.wml");
164  /**
165   * As described in <a href="http://www.ietf.org/rfc/rfc3023.txt">RFC 3023</a>, this constant
166   * ({@code text/xml}) is used for XML documents that are "readable by casual users."
167   * {@link #APPLICATION_XML_UTF_8} is provided for documents that are intended for applications.
168   */
169  public static final MediaType XML_UTF_8 = createConstantUtf8(TEXT_TYPE, "xml");
170
171  /* image types */
172  public static final MediaType BMP = createConstant(IMAGE_TYPE, "bmp");
173  /**
174   * The media type for the <a href="http://en.wikipedia.org/wiki/Camera_Image_File_Format">Canon
175   * Image File Format</a> ({@code crw} files), a widely-used "raw image" format for cameras. It is
176   * found in {@code /etc/mime.types}, e.g. in <href=
177   * "http://anonscm.debian.org/gitweb/?p=collab-maint/mime-support.git;a=blob;f=mime.types;hb=HEAD"
178   * >Debian 3.48-1</a>.
179   *
180   * @since 15.0
181   */
182  public static final MediaType CRW = createConstant(IMAGE_TYPE, "x-canon-crw");
183  public static final MediaType GIF = createConstant(IMAGE_TYPE, "gif");
184  public static final MediaType ICO = createConstant(IMAGE_TYPE, "vnd.microsoft.icon");
185  public static final MediaType JPEG = createConstant(IMAGE_TYPE, "jpeg");
186  public static final MediaType PNG = createConstant(IMAGE_TYPE, "png");
187  /**
188   * The media type for the Photoshop File Format ({@code psd} files) as defined by <a href=
189   * "http://www.iana.org/assignments/media-types/image/vnd.adobe.photoshop">IANA</a>, and found in
190   * {@code /etc/mime.types}, e.g. <a href=
191   * "http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types"></a> of the Apache
192   * <a href="http://httpd.apache.org/">HTTPD project</a>; for the specification, see
193   * <href="http://www.adobe.com/devnet-apps/photoshop/fileformatashtml/PhotoshopFileFormats.htm">
194   * Adobe Photoshop Document Format</a> and <a href=
195   * "http://en.wikipedia.org/wiki/Adobe_Photoshop#File_format">Wikipedia</a>; this is the regular
196   * output/input of Photoshop (which can also export to various image formats; note that files with
197   * extension "PSB" are in a distinct but related format).
198   * <p>This is a more recent replacement for the older, experimental type
199   * {@code x-photoshop}: <a href="http://tools.ietf.org/html/rfc2046#section-6">RFC-2046.6</a>.
200   *
201   * @since 15.0
202   */
203  public static final MediaType PSD = createConstant(IMAGE_TYPE, "vnd.adobe.photoshop");
204  public static final MediaType SVG_UTF_8 = createConstantUtf8(IMAGE_TYPE, "svg+xml");
205  public static final MediaType TIFF = createConstant(IMAGE_TYPE, "tiff");
206  public static final MediaType WEBP = createConstant(IMAGE_TYPE, "webp");
207
208  /* audio types */
209  public static final MediaType MP4_AUDIO = createConstant(AUDIO_TYPE, "mp4");
210  public static final MediaType MPEG_AUDIO = createConstant(AUDIO_TYPE, "mpeg");
211  public static final MediaType OGG_AUDIO = createConstant(AUDIO_TYPE, "ogg");
212  public static final MediaType WEBM_AUDIO = createConstant(AUDIO_TYPE, "webm");
213
214  /* video types */
215  public static final MediaType MP4_VIDEO = createConstant(VIDEO_TYPE, "mp4");
216  public static final MediaType MPEG_VIDEO = createConstant(VIDEO_TYPE, "mpeg");
217  public static final MediaType OGG_VIDEO = createConstant(VIDEO_TYPE, "ogg");
218  public static final MediaType QUICKTIME = createConstant(VIDEO_TYPE, "quicktime");
219  public static final MediaType WEBM_VIDEO = createConstant(VIDEO_TYPE, "webm");
220  public static final MediaType WMV = createConstant(VIDEO_TYPE, "x-ms-wmv");
221
222  /* application types */
223  /**
224   * As described in <a href="http://www.ietf.org/rfc/rfc3023.txt">RFC 3023</a>, this constant
225   * ({@code application/xml}) is used for XML documents that are "unreadable by casual users."
226   * {@link #XML_UTF_8} is provided for documents that may be read by users.
227   */
228  public static final MediaType APPLICATION_XML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xml");
229  public static final MediaType ATOM_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "atom+xml");
230  public static final MediaType BZIP2 = createConstant(APPLICATION_TYPE, "x-bzip2");
231
232  /**
233   * Media type for <a href="https://www.dartlang.org/articles/embedding-in-html/">dart files</a>.
234   *
235   * @since 19.0
236   */
237  public static final MediaType DART_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "dart");
238
239  /**
240   * Media type for <a href="https://goo.gl/dNnKKj">Apple Passbook</a>.
241   *
242   * @since 19.0
243   */
244  public static final MediaType APPLE_PASSBOOK = createConstant(APPLICATION_TYPE,
245      "vnd.apple.pkpass");
246
247  /**
248   * Media type for <a href="http://en.wikipedia.org/wiki/Embedded_OpenType">Embedded OpenType</a>
249   * fonts. This is
250   * <a href="http://www.iana.org/assignments/media-types/application/vnd.ms-fontobject">registered
251   * </a> with the IANA.
252   *
253   * @since 17.0
254   */
255  public static final MediaType EOT = createConstant(APPLICATION_TYPE, "vnd.ms-fontobject");
256  /**
257   * As described in the <a href="http://idpf.org/epub">International Digital Publishing Forum</a>
258   * EPUB is the distribution and interchange format standard for digital publications and
259   * documents. This media type is defined in the
260   * <a href="http://www.idpf.org/epub/30/spec/epub30-ocf.html">EPUB Open Container Format</a>
261   * specification.
262   *
263   * @since 15.0
264   */
265  public static final MediaType EPUB = createConstant(APPLICATION_TYPE, "epub+zip");
266  public static final MediaType FORM_DATA = createConstant(APPLICATION_TYPE,
267      "x-www-form-urlencoded");
268  /**
269   * As described in <a href="https://www.rsa.com/rsalabs/node.asp?id=2138">PKCS #12: Personal
270   * Information Exchange Syntax Standard</a>, PKCS #12 defines an archive file format for storing
271   * many cryptography objects as a single file.
272   *
273   * @since 15.0
274   */
275  public static final MediaType KEY_ARCHIVE = createConstant(APPLICATION_TYPE, "pkcs12");
276  /**
277   * This is a non-standard media type, but is commonly used in serving hosted binary files as it is
278   * <a href="http://code.google.com/p/browsersec/wiki/Part2#Survey_of_content_sniffing_behaviors">
279   * known not to trigger content sniffing in current browsers</a>. It <i>should not</i> be used in
280   * other situations as it is not specified by any RFC and does not appear in the <a href=
281   * "http://www.iana.org/assignments/media-types">/IANA MIME Media Types</a> list. Consider
282   * {@link #OCTET_STREAM} for binary data that is not being served to a browser.
283   *
284   *
285   * @since 14.0
286   */
287  public static final MediaType APPLICATION_BINARY = createConstant(APPLICATION_TYPE, "binary");
288  public static final MediaType GZIP = createConstant(APPLICATION_TYPE, "x-gzip");
289   /**
290    * <a href="http://www.rfc-editor.org/rfc/rfc4329.txt">RFC 4329</a> declares this to be the
291    * correct media type for JavaScript, but {@link #TEXT_JAVASCRIPT_UTF_8 text/javascript} may be
292    * necessary in certain situations for compatibility.
293    */
294  public static final MediaType JAVASCRIPT_UTF_8 =
295      createConstantUtf8(APPLICATION_TYPE, "javascript");
296  public static final MediaType JSON_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "json");
297  /**
298   * Media type for the
299   * <a href="http://www.w3.org/TR/appmanifest/">Manifest for a web application</a>.
300   *
301   * @since 19.0
302   */
303  public static final MediaType MANIFEST_JSON_UTF_8 =
304      createConstantUtf8(APPLICATION_TYPE, "manifest+json");
305  public static final MediaType KML = createConstant(APPLICATION_TYPE, "vnd.google-earth.kml+xml");
306  public static final MediaType KMZ = createConstant(APPLICATION_TYPE, "vnd.google-earth.kmz");
307  public static final MediaType MBOX = createConstant(APPLICATION_TYPE, "mbox");
308
309  /**
310   * Media type for
311   * <a href="http://goo.gl/1pGBFm">Apple over-the-air mobile configuration profiles</a>.
312   *
313   * @since 18.0
314   */
315  public static final MediaType APPLE_MOBILE_CONFIG =
316      createConstant(APPLICATION_TYPE, "x-apple-aspen-config");
317  public static final MediaType MICROSOFT_EXCEL = createConstant(APPLICATION_TYPE, "vnd.ms-excel");
318  public static final MediaType MICROSOFT_POWERPOINT =
319      createConstant(APPLICATION_TYPE, "vnd.ms-powerpoint");
320  public static final MediaType MICROSOFT_WORD = createConstant(APPLICATION_TYPE, "msword");
321  public static final MediaType OCTET_STREAM = createConstant(APPLICATION_TYPE, "octet-stream");
322  public static final MediaType OGG_CONTAINER = createConstant(APPLICATION_TYPE, "ogg");
323  public static final MediaType OOXML_DOCUMENT = createConstant(APPLICATION_TYPE,
324      "vnd.openxmlformats-officedocument.wordprocessingml.document");
325  public static final MediaType OOXML_PRESENTATION = createConstant(APPLICATION_TYPE,
326      "vnd.openxmlformats-officedocument.presentationml.presentation");
327  public static final MediaType OOXML_SHEET =
328      createConstant(APPLICATION_TYPE, "vnd.openxmlformats-officedocument.spreadsheetml.sheet");
329  public static final MediaType OPENDOCUMENT_GRAPHICS =
330      createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.graphics");
331  public static final MediaType OPENDOCUMENT_PRESENTATION =
332      createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.presentation");
333  public static final MediaType OPENDOCUMENT_SPREADSHEET =
334      createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.spreadsheet");
335  public static final MediaType OPENDOCUMENT_TEXT =
336      createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.text");
337  public static final MediaType PDF = createConstant(APPLICATION_TYPE, "pdf");
338  public static final MediaType POSTSCRIPT = createConstant(APPLICATION_TYPE, "postscript");
339  /**
340   * <a href="http://tools.ietf.org/html/draft-rfernando-protocol-buffers-00">Protocol buffers</a>
341   *
342   * @since 15.0
343   */
344  public static final MediaType PROTOBUF = createConstant(APPLICATION_TYPE, "protobuf");
345  public static final MediaType RDF_XML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "rdf+xml");
346  public static final MediaType RTF_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "rtf");
347  /**
348   * Media type for SFNT fonts (which includes
349   * <a href="http://en.wikipedia.org/wiki/TrueType/">TrueType</a> and
350   * <a href="http://en.wikipedia.org/wiki/OpenType/">OpenType</a> fonts). This is
351   * <a href="http://www.iana.org/assignments/media-types/application/font-sfnt">registered</a>
352   * with the IANA.
353   *
354   * @since 17.0
355   */
356  public static final MediaType SFNT = createConstant(APPLICATION_TYPE, "font-sfnt");
357  public static final MediaType SHOCKWAVE_FLASH = createConstant(APPLICATION_TYPE,
358      "x-shockwave-flash");
359  public static final MediaType SKETCHUP = createConstant(APPLICATION_TYPE, "vnd.sketchup.skp");
360  public static final MediaType TAR = createConstant(APPLICATION_TYPE, "x-tar");
361  /**
362   * Media type for the
363   * <a href="http://en.wikipedia.org/wiki/Web_Open_Font_Format">Web Open Font Format</a> (WOFF)
364   * <a href="http://www.w3.org/TR/WOFF/">defined</a> by the W3C. This is
365   * <a href="http://www.iana.org/assignments/media-types/application/font-woff">registered</a>
366   * with the IANA.
367   *
368   * @since 17.0
369   */
370  public static final MediaType WOFF = createConstant(APPLICATION_TYPE, "font-woff");
371  public static final MediaType XHTML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xhtml+xml");
372  /**
373   * Media type for Extensible Resource Descriptors. This is not yet registered with the IANA, but
374   * it is specified by OASIS in the
375   * <a href="http://docs.oasis-open.org/xri/xrd/v1.0/cd02/xrd-1.0-cd02.html"> XRD definition</a>
376   * and implemented in projects such as
377   * <a href="http://code.google.com/p/webfinger/">WebFinger</a>.
378   */
379  public static final MediaType XRD_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xrd+xml");
380  public static final MediaType ZIP = createConstant(APPLICATION_TYPE, "zip");
381
382  private final String type;
383  private final String subtype;
384  private final ImmutableListMultimap<String, String> parameters;
385
386  private String toString;
387
388  private int hashCode;
389
390  private MediaType(String type, String subtype,
391      ImmutableListMultimap<String, String> parameters) {
392    this.type = type;
393    this.subtype = subtype;
394    this.parameters = parameters;
395  }
396
397  /** Returns the top-level media type.  For example, {@code "text"} in {@code "text/plain"}. */
398  public String type() {
399    return type;
400  }
401
402  /** Returns the media subtype.  For example, {@code "plain"} in {@code "text/plain"}. */
403  public String subtype() {
404    return subtype;
405  }
406
407  /** Returns a multimap containing the parameters of this media type. */
408  public ImmutableListMultimap<String, String> parameters() {
409    return parameters;
410  }
411
412  private Map<String, ImmutableMultiset<String>> parametersAsMap() {
413    return Maps.transformValues(parameters.asMap(),
414        new Function<Collection<String>, ImmutableMultiset<String>>() {
415          @Override public ImmutableMultiset<String> apply(Collection<String> input) {
416            return ImmutableMultiset.copyOf(input);
417          }
418        });
419  }
420
421  /**
422   * Returns an optional charset for the value of the charset parameter if it is specified.
423   *
424   * @throws IllegalStateException if multiple charset values have been set for this media type
425   * @throws IllegalCharsetNameException if a charset value is present, but illegal
426   * @throws UnsupportedCharsetException if a charset value is present, but no support is available
427   *     in this instance of the Java virtual machine
428   */
429  public Optional<Charset> charset() {
430    ImmutableSet<String> charsetValues = ImmutableSet.copyOf(parameters.get(CHARSET_ATTRIBUTE));
431    switch (charsetValues.size()) {
432      case 0:
433        return Optional.absent();
434      case 1:
435        return Optional.of(Charset.forName(Iterables.getOnlyElement(charsetValues)));
436      default:
437        throw new IllegalStateException("Multiple charset values defined: " + charsetValues);
438    }
439  }
440
441  /**
442   * Returns a new instance with the same type and subtype as this instance, but without any
443   * parameters.
444   */
445  public MediaType withoutParameters() {
446    return parameters.isEmpty() ? this : create(type, subtype);
447  }
448
449  /**
450   * <em>Replaces</em> all parameters with the given parameters.
451   *
452   * @throws IllegalArgumentException if any parameter or value is invalid
453   */
454  public MediaType withParameters(Multimap<String, String> parameters) {
455    return create(type, subtype, parameters);
456  }
457
458  /**
459   * <em>Replaces</em> all parameters with the given attribute with a single parameter with the
460   * given value. If multiple parameters with the same attributes are necessary use
461   * {@link #withParameters}. Prefer {@link #withCharset} for setting the {@code charset} parameter
462   * when using a {@link Charset} object.
463   *
464   * @throws IllegalArgumentException if either {@code attribute} or {@code value} is invalid
465   */
466  public MediaType withParameter(String attribute, String value) {
467    checkNotNull(attribute);
468    checkNotNull(value);
469    String normalizedAttribute = normalizeToken(attribute);
470    ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
471    for (Entry<String, String> entry : parameters.entries()) {
472      String key = entry.getKey();
473      if (!normalizedAttribute.equals(key)) {
474        builder.put(key, entry.getValue());
475      }
476    }
477    builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value));
478    MediaType mediaType = new MediaType(type, subtype, builder.build());
479    // Return one of the constants if the media type is a known type.
480    return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
481  }
482
483  /**
484   * Returns a new instance with the same type and subtype as this instance, with the
485   * {@code charset} parameter set to the {@link Charset#name name} of the given charset. Only one
486   * {@code charset} parameter will be present on the new instance regardless of the number set on
487   * this one.
488   *
489   * <p>If a charset must be specified that is not supported on this JVM (and thus is not
490   * representable as a {@link Charset} instance, use {@link #withParameter}.
491   */
492  public MediaType withCharset(Charset charset) {
493    checkNotNull(charset);
494    return withParameter(CHARSET_ATTRIBUTE, charset.name());
495  }
496
497  /** Returns true if either the type or subtype is the wildcard. */
498  public boolean hasWildcard() {
499    return WILDCARD.equals(type) || WILDCARD.equals(subtype);
500  }
501
502  /**
503   * Returns {@code true} if this instance falls within the range (as defined by
504   * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">the HTTP Accept header</a>)
505   * given by the argument according to three criteria:
506   *
507   * <ol>
508   * <li>The type of the argument is the wildcard or equal to the type of this instance.
509   * <li>The subtype of the argument is the wildcard or equal to the subtype of this instance.
510   * <li>All of the parameters present in the argument are present in this instance.
511   * </ol>
512   *
513   * <p>For example: <pre>   {@code
514   *   PLAIN_TEXT_UTF_8.is(PLAIN_TEXT_UTF_8) // true
515   *   PLAIN_TEXT_UTF_8.is(HTML_UTF_8) // false
516   *   PLAIN_TEXT_UTF_8.is(ANY_TYPE) // true
517   *   PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE) // true
518   *   PLAIN_TEXT_UTF_8.is(ANY_IMAGE_TYPE) // false
519   *   PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE.withCharset(UTF_8)) // true
520   *   PLAIN_TEXT_UTF_8.withoutParameters().is(ANY_TEXT_TYPE.withCharset(UTF_8)) // false
521   *   PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE.withCharset(UTF_16)) // false}</pre>
522   *
523   * <p>Note that while it is possible to have the same parameter declared multiple times within a
524   * media type this method does not consider the number of occurrences of a parameter.  For
525   * example, {@code "text/plain; charset=UTF-8"} satisfies
526   * {@code "text/plain; charset=UTF-8; charset=UTF-8"}.
527   */
528  public boolean is(MediaType mediaTypeRange) {
529    return (mediaTypeRange.type.equals(WILDCARD) || mediaTypeRange.type.equals(this.type))
530        && (mediaTypeRange.subtype.equals(WILDCARD) || mediaTypeRange.subtype.equals(this.subtype))
531        && this.parameters.entries().containsAll(mediaTypeRange.parameters.entries());
532  }
533
534  /**
535   * Creates a new media type with the given type and subtype.
536   *
537   * @throws IllegalArgumentException if type or subtype is invalid or if a wildcard is used for the
538   * type, but not the subtype.
539   */
540  public static MediaType create(String type, String subtype) {
541    return create(type, subtype, ImmutableListMultimap.<String, String>of());
542  }
543
544  /**
545   * Creates a media type with the "application" type and the given subtype.
546   *
547   * @throws IllegalArgumentException if subtype is invalid
548   */
549  static MediaType createApplicationType(String subtype) {
550    return create(APPLICATION_TYPE, subtype);
551  }
552
553  /**
554   * Creates a media type with the "audio" type and the given subtype.
555   *
556   * @throws IllegalArgumentException if subtype is invalid
557   */
558  static MediaType createAudioType(String subtype) {
559    return create(AUDIO_TYPE, subtype);
560  }
561
562  /**
563   * Creates a media type with the "image" type and the given subtype.
564   *
565   * @throws IllegalArgumentException if subtype is invalid
566   */
567  static MediaType createImageType(String subtype) {
568    return create(IMAGE_TYPE, subtype);
569  }
570
571  /**
572   * Creates a media type with the "text" type and the given subtype.
573   *
574   * @throws IllegalArgumentException if subtype is invalid
575   */
576  static MediaType createTextType(String subtype) {
577    return create(TEXT_TYPE, subtype);
578  }
579
580  /**
581   * Creates a media type with the "video" type and the given subtype.
582   *
583   * @throws IllegalArgumentException if subtype is invalid
584   */
585  static MediaType createVideoType(String subtype) {
586    return create(VIDEO_TYPE, subtype);
587  }
588
589  private static MediaType create(String type, String subtype,
590      Multimap<String, String> parameters) {
591    checkNotNull(type);
592    checkNotNull(subtype);
593    checkNotNull(parameters);
594    String normalizedType = normalizeToken(type);
595    String normalizedSubtype = normalizeToken(subtype);
596    checkArgument(!WILDCARD.equals(normalizedType) || WILDCARD.equals(normalizedSubtype),
597        "A wildcard type cannot be used with a non-wildcard subtype");
598    ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
599    for (Entry<String, String> entry : parameters.entries()) {
600      String attribute = normalizeToken(entry.getKey());
601      builder.put(attribute, normalizeParameterValue(attribute, entry.getValue()));
602    }
603    MediaType mediaType = new MediaType(normalizedType, normalizedSubtype, builder.build());
604    // Return one of the constants if the media type is a known type.
605    return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
606  }
607
608  private static String normalizeToken(String token) {
609    checkArgument(TOKEN_MATCHER.matchesAllOf(token));
610    return Ascii.toLowerCase(token);
611  }
612
613  private static String normalizeParameterValue(String attribute, String value) {
614    return CHARSET_ATTRIBUTE.equals(attribute) ? Ascii.toLowerCase(value) : value;
615  }
616
617  /**
618   * Parses a media type from its string representation.
619   *
620   * @throws IllegalArgumentException if the input is not parsable
621   */
622  public static MediaType parse(String input) {
623    checkNotNull(input);
624    Tokenizer tokenizer = new Tokenizer(input);
625    try {
626      String type = tokenizer.consumeToken(TOKEN_MATCHER);
627      tokenizer.consumeCharacter('/');
628      String subtype = tokenizer.consumeToken(TOKEN_MATCHER);
629      ImmutableListMultimap.Builder<String, String> parameters = ImmutableListMultimap.builder();
630      while (tokenizer.hasMore()) {
631        tokenizer.consumeCharacter(';');
632        tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE);
633        String attribute = tokenizer.consumeToken(TOKEN_MATCHER);
634        tokenizer.consumeCharacter('=');
635        final String value;
636        if ('"' == tokenizer.previewChar()) {
637          tokenizer.consumeCharacter('"');
638          StringBuilder valueBuilder = new StringBuilder();
639          while ('"' != tokenizer.previewChar()) {
640            if ('\\' == tokenizer.previewChar()) {
641              tokenizer.consumeCharacter('\\');
642              valueBuilder.append(tokenizer.consumeCharacter(ASCII));
643            } else {
644              valueBuilder.append(tokenizer.consumeToken(QUOTED_TEXT_MATCHER));
645            }
646          }
647          value = valueBuilder.toString();
648          tokenizer.consumeCharacter('"');
649        } else {
650          value = tokenizer.consumeToken(TOKEN_MATCHER);
651        }
652        parameters.put(attribute, value);
653      }
654      return create(type, subtype, parameters.build());
655    } catch (IllegalStateException e) {
656      throw new IllegalArgumentException("Could not parse '" + input + "'", e);
657    }
658  }
659
660  private static final class Tokenizer {
661    final String input;
662    int position = 0;
663
664    Tokenizer(String input) {
665      this.input = input;
666    }
667
668    String consumeTokenIfPresent(CharMatcher matcher) {
669      checkState(hasMore());
670      int startPosition = position;
671      position = matcher.negate().indexIn(input, startPosition);
672      return hasMore() ? input.substring(startPosition, position) : input.substring(startPosition);
673    }
674
675    String consumeToken(CharMatcher matcher) {
676      int startPosition = position;
677      String token = consumeTokenIfPresent(matcher);
678      checkState(position != startPosition);
679      return token;
680    }
681
682    char consumeCharacter(CharMatcher matcher) {
683      checkState(hasMore());
684      char c = previewChar();
685      checkState(matcher.matches(c));
686      position++;
687      return c;
688    }
689
690    char consumeCharacter(char c) {
691      checkState(hasMore());
692      checkState(previewChar() == c);
693      position++;
694      return c;
695    }
696
697    char previewChar() {
698      checkState(hasMore());
699      return input.charAt(position);
700    }
701
702    boolean hasMore() {
703      return (position >= 0) && (position < input.length());
704    }
705  }
706
707  @Override public boolean equals(@Nullable Object obj) {
708    if (obj == this) {
709      return true;
710    } else if (obj instanceof MediaType) {
711      MediaType that = (MediaType) obj;
712      return this.type.equals(that.type)
713          && this.subtype.equals(that.subtype)
714          // compare parameters regardless of order
715          && this.parametersAsMap().equals(that.parametersAsMap());
716    } else {
717      return false;
718    }
719  }
720
721  @Override public int hashCode() {
722    // racy single-check idiom
723    int h = hashCode;
724    if (h == 0) {
725      h = Objects.hashCode(type, subtype, parametersAsMap());
726      hashCode = h;
727    }
728    return h;
729  }
730
731  private static final MapJoiner PARAMETER_JOINER = Joiner.on("; ").withKeyValueSeparator("=");
732
733  /**
734   * Returns the string representation of this media type in the format described in <a
735   * href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
736   */
737  @Override public String toString() {
738    // racy single-check idiom, safe because String is immutable
739    String result = toString;
740    if (result == null) {
741      result = computeToString();
742      toString = result;
743    }
744    return result;
745  }
746
747  private String computeToString() {
748    StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype);
749    if (!parameters.isEmpty()) {
750      builder.append("; ");
751      Multimap<String, String> quotedParameters = Multimaps.transformValues(parameters,
752          new Function<String, String>() {
753            @Override public String apply(String value) {
754              return TOKEN_MATCHER.matchesAllOf(value) ? value : escapeAndQuote(value);
755            }
756          });
757      PARAMETER_JOINER.appendTo(builder, quotedParameters.entries());
758    }
759    return builder.toString();
760  }
761
762  private static String escapeAndQuote(String value) {
763    StringBuilder escaped = new StringBuilder(value.length() + 16).append('"');
764    for (int i = 0; i < value.length(); i++) {
765      char ch = value.charAt(i);
766      if (ch == '\r' || ch == '\\' || ch == '"') {
767        escaped.append('\\');
768      }
769      escaped.append(ch);
770    }
771    return escaped.append('"').toString();
772  }
773
774}