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    
017    package com.google.common.net;
018    
019    import static com.google.common.base.CharMatcher.ASCII;
020    import static com.google.common.base.CharMatcher.JAVA_ISO_CONTROL;
021    import static com.google.common.base.Charsets.UTF_8;
022    import static com.google.common.base.Preconditions.checkArgument;
023    import static com.google.common.base.Preconditions.checkNotNull;
024    import static com.google.common.base.Preconditions.checkState;
025    
026    import com.google.common.annotations.Beta;
027    import com.google.common.annotations.GwtCompatible;
028    import com.google.common.base.Ascii;
029    import com.google.common.base.CharMatcher;
030    import com.google.common.base.Function;
031    import com.google.common.base.Joiner;
032    import com.google.common.base.Joiner.MapJoiner;
033    import com.google.common.base.Objects;
034    import com.google.common.base.Optional;
035    import com.google.common.collect.ImmutableListMultimap;
036    import com.google.common.collect.ImmutableMap;
037    import com.google.common.collect.ImmutableMultiset;
038    import com.google.common.collect.ImmutableSet;
039    import com.google.common.collect.Iterables;
040    import com.google.common.collect.Maps;
041    import com.google.common.collect.Multimap;
042    import com.google.common.collect.Multimaps;
043    
044    import java.nio.charset.Charset;
045    import java.nio.charset.IllegalCharsetNameException;
046    import java.nio.charset.UnsupportedCharsetException;
047    import java.util.Collection;
048    import java.util.Map;
049    import java.util.Map.Entry;
050    
051    import javax.annotation.Nullable;
052    import 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
083    public 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      /*
110       * The following constants are grouped by their type and ordered alphabetically by the constant
111       * name within that type. The constant name should be a sensible identifier that is closest to the
112       * "common name" of the media.  This is often, but not necessarily the same as the subtype.
113       *
114       * Be sure to declare all constants with the type and subtype in all lowercase.
115       *
116       * When adding constants, be sure to add an entry into the KNOWN_TYPES map. For types that
117       * take a charset (e.g. all text/* types), default to UTF-8 and suffix with "_UTF_8".
118       */
119    
120      public static final MediaType ANY_TYPE = createConstant(WILDCARD, WILDCARD);
121      public static final MediaType ANY_TEXT_TYPE = createConstant(TEXT_TYPE, WILDCARD);
122      public static final MediaType ANY_IMAGE_TYPE = createConstant(IMAGE_TYPE, WILDCARD);
123      public static final MediaType ANY_AUDIO_TYPE = createConstant(AUDIO_TYPE, WILDCARD);
124      public static final MediaType ANY_VIDEO_TYPE = createConstant(VIDEO_TYPE, WILDCARD);
125      public static final MediaType ANY_APPLICATION_TYPE = createConstant(APPLICATION_TYPE, WILDCARD);
126    
127      /* text types */
128      public static final MediaType CACHE_MANIFEST_UTF_8 =
129          createConstantUtf8(TEXT_TYPE, "cache-manifest");
130      public static final MediaType CSS_UTF_8 = createConstantUtf8(TEXT_TYPE, "css");
131      public static final MediaType CSV_UTF_8 = createConstantUtf8(TEXT_TYPE, "csv");
132      public static final MediaType HTML_UTF_8 = createConstantUtf8(TEXT_TYPE, "html");
133      public static final MediaType I_CALENDAR_UTF_8 = createConstantUtf8(TEXT_TYPE, "calendar");
134      public static final MediaType PLAIN_TEXT_UTF_8 = createConstantUtf8(TEXT_TYPE, "plain");
135      /**
136       * <a href="http://www.rfc-editor.org/rfc/rfc4329.txt">RFC 4329</a> declares
137       * {@link #JAVASCRIPT_UTF_8 application/javascript} to be the correct media type for JavaScript,
138       * but this may be necessary in certain situations for compatibility.
139       */
140      public static final MediaType TEXT_JAVASCRIPT_UTF_8 = createConstantUtf8(TEXT_TYPE, "javascript");
141      public static final MediaType VCARD_UTF_8 = createConstantUtf8(TEXT_TYPE, "vcard");
142      public static final MediaType XML_UTF_8 = createConstantUtf8(TEXT_TYPE, "xml");
143    
144      /* image types */
145      public static final MediaType GIF = createConstant(IMAGE_TYPE, "gif");
146      public static final MediaType ICO = createConstant(IMAGE_TYPE, "vnd.microsoft.icon");
147      public static final MediaType JPEG = createConstant(IMAGE_TYPE, "jpeg");
148      public static final MediaType PNG = createConstant(IMAGE_TYPE, "png");
149      public static final MediaType SVG_UTF_8 = createConstantUtf8(IMAGE_TYPE, "svg+xml");
150      public static final MediaType TIFF = createConstant(IMAGE_TYPE, "tiff");
151    
152      /* audio types */
153      public static final MediaType MP4_AUDIO = createConstant(AUDIO_TYPE, "mp4");
154      public static final MediaType MPEG_AUDIO = createConstant(AUDIO_TYPE, "mpeg");
155      public static final MediaType OGG_AUDIO = createConstant(AUDIO_TYPE, "ogg");
156      public static final MediaType WEBM_AUDIO = createConstant(AUDIO_TYPE, "webm");
157    
158      /* video types */
159      public static final MediaType MP4_VIDEO = createConstant(VIDEO_TYPE, "mp4");
160      public static final MediaType MPEG_VIDEO = createConstant(VIDEO_TYPE, "mpeg");
161      public static final MediaType OGG_VIDEO = createConstant(VIDEO_TYPE, "ogg");
162      public static final MediaType QUICKTIME = createConstant(VIDEO_TYPE, "quicktime");
163      public static final MediaType WEBM_VIDEO = createConstant(VIDEO_TYPE, "webm");
164      public static final MediaType WMV = createConstant(VIDEO_TYPE, "x-ms-wmv");
165    
166      /* application types */
167      public static final MediaType ATOM_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "atom+xml");
168      public static final MediaType BZIP2 = createConstant(APPLICATION_TYPE, "x-bzip2");
169      public static final MediaType FORM_DATA = createConstant(APPLICATION_TYPE,
170          "x-www-form-urlencoded");
171      public static final MediaType GZIP = createConstant(APPLICATION_TYPE, "x-gzip");
172       /**
173        * <a href="http://www.rfc-editor.org/rfc/rfc4329.txt">RFC 4329</a> declares this to be the
174        * correct media type for JavaScript, but {@link #TEXT_JAVASCRIPT_UTF_8 text/javascript} may be
175        * necessary in certain situations for compatibility.
176        */
177      public static final MediaType JAVASCRIPT_UTF_8 =
178          createConstantUtf8(APPLICATION_TYPE, "javascript");
179      public static final MediaType JSON_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "json");
180      public static final MediaType KML = createConstant(APPLICATION_TYPE, "vnd.google-earth.kml+xml");
181      public static final MediaType KMZ = createConstant(APPLICATION_TYPE, "vnd.google-earth.kmz");
182      public static final MediaType MICROSOFT_EXCEL = createConstant(APPLICATION_TYPE, "vnd.ms-excel");
183      public static final MediaType MICROSOFT_POWERPOINT =
184          createConstant(APPLICATION_TYPE, "vnd.ms-powerpoint");
185      public static final MediaType MICROSOFT_WORD = createConstant(APPLICATION_TYPE, "msword");
186      public static final MediaType OCTET_STREAM = createConstant(APPLICATION_TYPE, "octet-stream");
187      public static final MediaType OGG_CONTAINER = createConstant(APPLICATION_TYPE, "ogg");
188      public static final MediaType OOXML_DOCUMENT = createConstant(APPLICATION_TYPE,
189          "vnd.openxmlformats-officedocument.wordprocessingml.document");
190      public static final MediaType OOXML_PRESENTATION = createConstant(APPLICATION_TYPE,
191          "vnd.openxmlformats-officedocument.presentationml.presentation");
192      public static final MediaType OOXML_SHEET =
193          createConstant(APPLICATION_TYPE, "vnd.openxmlformats-officedocument.spreadsheetml.sheet");
194      public static final MediaType OPENDOCUMENT_GRAPHICS =
195          createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.graphics");
196      public static final MediaType OPENDOCUMENT_PRESENTATION =
197          createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.presentation");
198      public static final MediaType OPENDOCUMENT_SPREADSHEET =
199          createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.spreadsheet");
200      public static final MediaType OPENDOCUMENT_TEXT =
201          createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.text");
202      public static final MediaType PDF = createConstant(APPLICATION_TYPE, "pdf");
203      public static final MediaType POSTSCRIPT = createConstant(APPLICATION_TYPE, "postscript");
204      public static final MediaType RTF_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "rtf");
205      public static final MediaType SHOCKWAVE_FLASH = createConstant(APPLICATION_TYPE,
206          "x-shockwave-flash");
207      public static final MediaType TAR = createConstant(APPLICATION_TYPE, "x-tar");
208      public static final MediaType XHTML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xhtml+xml");
209      public static final MediaType ZIP = createConstant(APPLICATION_TYPE, "zip");
210    
211      private static final ImmutableMap<MediaType, MediaType> KNOWN_TYPES =
212          new ImmutableMap.Builder<MediaType, MediaType>()
213              .put(ANY_TYPE, ANY_TYPE)
214              .put(ANY_TEXT_TYPE, ANY_TEXT_TYPE)
215              .put(ANY_IMAGE_TYPE, ANY_IMAGE_TYPE)
216              .put(ANY_AUDIO_TYPE, ANY_AUDIO_TYPE)
217              .put(ANY_VIDEO_TYPE, ANY_VIDEO_TYPE)
218              .put(ANY_APPLICATION_TYPE, ANY_APPLICATION_TYPE)
219              /* text types */
220              .put(CACHE_MANIFEST_UTF_8, CACHE_MANIFEST_UTF_8)
221              .put(CSS_UTF_8, CSS_UTF_8)
222              .put(CSV_UTF_8, CSV_UTF_8)
223              .put(HTML_UTF_8, HTML_UTF_8)
224              .put(I_CALENDAR_UTF_8, I_CALENDAR_UTF_8)
225              .put(PLAIN_TEXT_UTF_8, PLAIN_TEXT_UTF_8)
226              .put(TEXT_JAVASCRIPT_UTF_8, TEXT_JAVASCRIPT_UTF_8)
227              .put(VCARD_UTF_8, VCARD_UTF_8)
228              .put(XML_UTF_8, XML_UTF_8)
229              /* image types */
230              .put(GIF, GIF)
231              .put(ICO, ICO)
232              .put(JPEG, JPEG)
233              .put(PNG, PNG)
234              .put(SVG_UTF_8, SVG_UTF_8)
235              .put(TIFF, TIFF)
236              /* audio types */
237              .put(MP4_AUDIO, MP4_AUDIO)
238              .put(MPEG_AUDIO, MPEG_AUDIO)
239              .put(OGG_AUDIO, OGG_AUDIO)
240              .put(WEBM_AUDIO, WEBM_AUDIO)
241              /* video types */
242              .put(MP4_VIDEO, MP4_VIDEO)
243              .put(MPEG_VIDEO, MPEG_VIDEO)
244              .put(OGG_VIDEO, OGG_VIDEO)
245              .put(QUICKTIME, QUICKTIME)
246              .put(WEBM_VIDEO, WEBM_VIDEO)
247              .put(WMV, WMV)
248              /* application types */
249              .put(ATOM_UTF_8, ATOM_UTF_8)
250              .put(BZIP2, BZIP2)
251              .put(FORM_DATA, FORM_DATA)
252              .put(GZIP, GZIP)
253              .put(JAVASCRIPT_UTF_8, JAVASCRIPT_UTF_8)
254              .put(JSON_UTF_8, JSON_UTF_8)
255              .put(KML, KML)
256              .put(KMZ, KMZ)
257              .put(MICROSOFT_EXCEL, MICROSOFT_EXCEL)
258              .put(MICROSOFT_POWERPOINT, MICROSOFT_POWERPOINT)
259              .put(MICROSOFT_WORD, MICROSOFT_WORD)
260              .put(OCTET_STREAM, OCTET_STREAM)
261              .put(OGG_CONTAINER, OGG_CONTAINER)
262              .put(OOXML_DOCUMENT, OOXML_DOCUMENT)
263              .put(OOXML_PRESENTATION, OOXML_PRESENTATION)
264              .put(OOXML_SHEET, OOXML_SHEET)
265              .put(OPENDOCUMENT_GRAPHICS, OPENDOCUMENT_GRAPHICS)
266              .put(OPENDOCUMENT_PRESENTATION, OPENDOCUMENT_PRESENTATION)
267              .put(OPENDOCUMENT_SPREADSHEET, OPENDOCUMENT_SPREADSHEET)
268              .put(OPENDOCUMENT_TEXT, OPENDOCUMENT_TEXT)
269              .put(PDF, PDF)
270              .put(POSTSCRIPT, POSTSCRIPT)
271              .put(RTF_UTF_8, RTF_UTF_8)
272              .put(SHOCKWAVE_FLASH, SHOCKWAVE_FLASH)
273              .put(TAR, TAR)
274              .put(XHTML_UTF_8, XHTML_UTF_8)
275              .put(ZIP, ZIP)
276              .build();
277    
278      private final String type;
279      private final String subtype;
280      private final ImmutableListMultimap<String, String> parameters;
281    
282      private MediaType(String type, String subtype,
283          ImmutableListMultimap<String, String> parameters) {
284        this.type = type;
285        this.subtype = subtype;
286        this.parameters = parameters;
287      }
288    
289      private static MediaType createConstant(String type, String subtype) {
290        return new MediaType(type, subtype, ImmutableListMultimap.<String, String>of());
291      }
292    
293      private static MediaType createConstantUtf8(String type, String subtype) {
294        return new MediaType(type, subtype, UTF_8_CONSTANT_PARAMETERS);
295      }
296    
297      /** Returns the top-level media type.  For example, {@code "text"} in {@code "text/plain"}. */
298      public String type() {
299        return type;
300      }
301    
302      /** Returns the media subtype.  For example, {@code "plain"} in {@code "text/plain"}. */
303      public String subtype() {
304        return subtype;
305      }
306    
307      /** Returns a multimap containing the parameters of this media type. */
308      public ImmutableListMultimap<String, String> parameters() {
309        return parameters;
310      }
311    
312      private Map<String, ImmutableMultiset<String>> parametersAsMap() {
313        return Maps.transformValues(parameters.asMap(),
314            new Function<Collection<String>, ImmutableMultiset<String>>() {
315              @Override public ImmutableMultiset<String> apply(Collection<String> input) {
316                return ImmutableMultiset.copyOf(input);
317              }
318            });
319      }
320    
321      /**
322       * Returns an optional charset for the value of the charset parameter if it is specified.
323       *
324       * @throws IllegalStateException if multiple charset values have been set for this media type
325       * @throws IllegalCharsetNameException if a charset value is present, but illegal
326       * @throws UnsupportedCharsetException if a charset value is present, but no support is available
327       *     in this instance of the Java virtual machine
328       */
329      public Optional<Charset> charset() {
330        ImmutableSet<String> charsetValues = ImmutableSet.copyOf(parameters.get(CHARSET_ATTRIBUTE));
331        switch (charsetValues.size()) {
332          case 0:
333            return Optional.absent();
334          case 1:
335            return Optional.of(Charset.forName(Iterables.getOnlyElement(charsetValues)));
336          default:
337            throw new IllegalStateException("Multiple charset values defined: " + charsetValues);
338        }
339      }
340    
341      /**
342       * Returns a new instance with the same type and subtype as this instance, but without any
343       * parameters.
344       */
345      public MediaType withoutParameters() {
346        return parameters.isEmpty() ? this : create(type, subtype);
347      }
348    
349      /**
350       * <em>Replaces</em> all parameters with the given parameters.
351       *
352       * @throws IllegalArgumentException if any parameter or value is invalid
353       */
354      public MediaType withParameters(Multimap<String, String> parameters) {
355        return create(type, subtype, parameters);
356      }
357    
358      /**
359       * <em>Replaces</em> all parameters with the given attribute with a single parameter with the
360       * given value. If multiple parameters with the same attributes are necessary use
361       * {@link #withParameters}. Prefer {@link #withCharset} for setting the {@code charset} parameter
362       * when using a {@link Charset} object.
363       *
364       * @throws IllegalArgumentException if either {@code attribute} or {@code value} is invalid
365       */
366      public MediaType withParameter(String attribute, String value) {
367        checkNotNull(attribute);
368        checkNotNull(value);
369        String normalizedAttribute = normalizeToken(attribute);
370        ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
371        for (Entry<String, String> entry : parameters.entries()) {
372          String key = entry.getKey();
373          if (!normalizedAttribute.equals(key)) {
374            builder.put(key, entry.getValue());
375          }
376        }
377        builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value));
378        MediaType mediaType = new MediaType(type, subtype, builder.build());
379        // Return one of the constants if the media type is a known type.
380        return Objects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
381      }
382    
383      /**
384       * Returns a new instance with the same type and subtype as this instance, with the
385       * {@code charset} parameter set to the {@link Charset#name name} of the given charset. Only one
386       * {@code charset} parameter will be present on the new instance regardless of the number set on
387       * this one.
388       *
389       * <p>If a charset must be specified that is not supported on this JVM (and thus is not
390       * representable as a {@link Charset} instance, use {@link #withParameter}.
391       */
392      public MediaType withCharset(Charset charset) {
393        checkNotNull(charset);
394        return withParameter(CHARSET_ATTRIBUTE, charset.name());
395      }
396    
397      /** Returns true if either the type or subtype is the wildcard. */
398      public boolean hasWildcard() {
399        return WILDCARD.equals(type) || WILDCARD.equals(subtype);
400      }
401    
402      /**
403       * Returns {@code true} if this instance falls within the range (as defined by
404       * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">the HTTP Accept header</a>)
405       * given by the argument according to three criteria:
406       *
407       * <ol>
408       * <li>The type of the argument is the wildcard or equal to the type of this instance.
409       * <li>The subtype of the argument is the wildcard or equal to the subtype of this instance.
410       * <li>All of the parameters present in the argument are present in this instance.
411       * </ol>
412       *
413       * For example: <pre>   {@code
414       *   PLAIN_TEXT_UTF_8.is(PLAIN_TEXT_UTF_8) // true
415       *   PLAIN_TEXT_UTF_8.is(HTML_UTF_8) // false
416       *   PLAIN_TEXT_UTF_8.is(ANY_TYPE) // true
417       *   PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE) // true
418       *   PLAIN_TEXT_UTF_8.is(ANY_IMAGE_TYPE) // false
419       *   PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE.withCharset(UTF_8)) // true
420       *   PLAIN_TEXT_UTF_8.withoutParameters().is(ANY_TEXT_TYPE.withCharset(UTF_8)) // false
421       *   PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE.withCharset(UTF_16)) // false}</pre>
422       *
423       * <p>Note that while it is possible to have the same parameter declared multiple times within a
424       * media type this method does not consider the number of occurrences of a parameter.  For
425       * example, {@code "text/plain; charset=UTF-8"} satisfies
426       * {@code "text/plain; charset=UTF-8; charset=UTF-8"}.
427       */
428      public boolean is(MediaType mediaTypeRange) {
429        return (mediaTypeRange.type.equals(WILDCARD) || mediaTypeRange.type.equals(this.type))
430            && (mediaTypeRange.subtype.equals(WILDCARD) || mediaTypeRange.subtype.equals(this.subtype))
431            && this.parameters.entries().containsAll(mediaTypeRange.parameters.entries());
432      }
433    
434      /**
435       * Creates a new media type with the given type and subtype.
436       *
437       * @throws IllegalArgumentException if type or subtype is invalid or if a wildcard is used for the
438       * type, but not the subtype.
439       */
440      public static MediaType create(String type, String subtype) {
441        return create(type, subtype, ImmutableListMultimap.<String, String>of());
442      }
443    
444      /**
445       * Creates a media type with the "application" type and the given subtype.
446       *
447       * @throws IllegalArgumentException if subtype is invalid
448       */
449      static MediaType createApplicationType(String subtype) {
450        return create(APPLICATION_TYPE, subtype);
451      }
452    
453      /**
454       * Creates a media type with the "audio" type and the given subtype.
455       *
456       * @throws IllegalArgumentException if subtype is invalid
457       */
458      static MediaType createAudioType(String subtype) {
459        return create(AUDIO_TYPE, subtype);
460      }
461    
462      /**
463       * Creates a media type with the "image" type and the given subtype.
464       *
465       * @throws IllegalArgumentException if subtype is invalid
466       */
467      static MediaType createImageType(String subtype) {
468        return create(IMAGE_TYPE, subtype);
469      }
470    
471      /**
472       * Creates a media type with the "text" type and the given subtype.
473       *
474       * @throws IllegalArgumentException if subtype is invalid
475       */
476      static MediaType createTextType(String subtype) {
477        return create(TEXT_TYPE, subtype);
478      }
479    
480      /**
481       * Creates a media type with the "video" type and the given subtype.
482       *
483       * @throws IllegalArgumentException if subtype is invalid
484       */
485      static MediaType createVideoType(String subtype) {
486        return create(VIDEO_TYPE, subtype);
487      }
488    
489      private static MediaType create(String type, String subtype,
490          Multimap<String, String> parameters) {
491        checkNotNull(type);
492        checkNotNull(subtype);
493        checkNotNull(parameters);
494        String normalizedType = normalizeToken(type);
495        String normalizedSubtype = normalizeToken(subtype);
496        checkArgument(!WILDCARD.equals(normalizedType) || WILDCARD.equals(normalizedSubtype),
497            "A wildcard type cannot be used with a non-wildcard subtype");
498        ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
499        for (Entry<String, String> entry : parameters.entries()) {
500          String attribute = normalizeToken(entry.getKey());
501          builder.put(attribute, normalizeParameterValue(attribute, entry.getValue()));
502        }
503        MediaType mediaType = new MediaType(normalizedType, normalizedSubtype, builder.build());
504        // Return one of the constants if the media type is a known type.
505        return Objects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
506      }
507    
508      private static String normalizeToken(String token) {
509        checkArgument(TOKEN_MATCHER.matchesAllOf(token));
510        return Ascii.toLowerCase(token);
511      }
512    
513      private static String normalizeParameterValue(String attribute, String value) {
514        return CHARSET_ATTRIBUTE.equals(attribute) ? Ascii.toLowerCase(value) : value;
515      }
516    
517      /**
518       * Parses a media type from its string representation.
519       *
520       * @throws IllegalArgumentException if the input is not parsable
521       */
522      public static MediaType parse(String input) {
523        checkNotNull(input);
524        Tokenizer tokenizer = new Tokenizer(input);
525        try {
526          String type = tokenizer.consumeToken(TOKEN_MATCHER);
527          tokenizer.consumeCharacter('/');
528          String subtype = tokenizer.consumeToken(TOKEN_MATCHER);
529          ImmutableListMultimap.Builder<String, String> parameters = ImmutableListMultimap.builder();
530          while (tokenizer.hasMore()) {
531            tokenizer.consumeCharacter(';');
532            tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE);
533            String attribute = tokenizer.consumeToken(TOKEN_MATCHER);
534            tokenizer.consumeCharacter('=');
535            final String value;
536            if ('"' == tokenizer.previewChar()) {
537              tokenizer.consumeCharacter('"');
538              StringBuilder valueBuilder = new StringBuilder();
539              while ('"' != tokenizer.previewChar()) {
540                if ('\\' == tokenizer.previewChar()) {
541                  tokenizer.consumeCharacter('\\');
542                  valueBuilder.append(tokenizer.consumeCharacter(ASCII));
543                } else {
544                  valueBuilder.append(tokenizer.consumeToken(QUOTED_TEXT_MATCHER));
545                }
546              }
547              value = valueBuilder.toString();
548              tokenizer.consumeCharacter('"');
549            } else {
550              value = tokenizer.consumeToken(TOKEN_MATCHER);
551            }
552            parameters.put(attribute, value);
553          }
554          return create(type, subtype, parameters.build());
555        } catch (IllegalStateException e) {
556          throw new IllegalArgumentException(e);
557        }
558      }
559    
560      private static final class Tokenizer {
561        final String input;
562        int position = 0;
563    
564        Tokenizer(String input) {
565          this.input = input;
566        }
567    
568        String consumeTokenIfPresent(CharMatcher matcher) {
569          checkState(hasMore());
570          int startPosition = position;
571          position = matcher.negate().indexIn(input, startPosition);
572          return hasMore() ? input.substring(startPosition, position) : input.substring(startPosition);
573        }
574    
575        String consumeToken(CharMatcher matcher) {
576          int startPosition = position;
577          String token = consumeTokenIfPresent(matcher);
578          checkState(position != startPosition);
579          return token;
580        }
581    
582        char consumeCharacter(CharMatcher matcher) {
583          checkState(hasMore());
584          char c = previewChar();
585          checkState(matcher.matches(c));
586          position++;
587          return c;
588        }
589    
590        char consumeCharacter(char c) {
591          checkState(hasMore());
592          checkState(previewChar() == c);
593          position++;
594          return c;
595        }
596    
597        char previewChar() {
598          checkState(hasMore());
599          return input.charAt(position);
600        }
601    
602        boolean hasMore() {
603          return (position >= 0) && (position < input.length());
604        }
605      }
606    
607      @Override public boolean equals(@Nullable Object obj) {
608        if (obj == this) {
609          return true;
610        } else if (obj instanceof MediaType) {
611          MediaType that = (MediaType) obj;
612          return this.type.equals(that.type)
613              && this.subtype.equals(that.subtype)
614              // compare parameters regardless of order
615              && this.parametersAsMap().equals(that.parametersAsMap());
616        } else {
617          return false;
618        }
619      }
620    
621      @Override public int hashCode() {
622        return Objects.hashCode(type, subtype, parametersAsMap());
623      }
624    
625      private static final MapJoiner PARAMETER_JOINER = Joiner.on("; ").withKeyValueSeparator("=");
626    
627      /**
628       * Returns the string representation of this media type in the format described in <a
629       * href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
630       */
631      @Override public String toString() {
632        StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype);
633        if (!parameters.isEmpty()) {
634          builder.append("; ");
635          Multimap<String, String> quotedParameters = Multimaps.transformValues(parameters,
636              new Function<String, String>() {
637                @Override public String apply(String value) {
638                  return TOKEN_MATCHER.matchesAllOf(value) ? value : escapeAndQuote(value);
639                }
640              });
641          PARAMETER_JOINER.appendTo(builder, quotedParameters.entries());
642        }
643        return builder.toString();
644      }
645    
646      private static String escapeAndQuote(String value) {
647        StringBuilder escaped = new StringBuilder(value.length() + 16).append('"');
648        for (char ch : value.toCharArray()) {
649          if (ch == '\r' || ch == '\\' || ch == '"') {
650            escaped.append('\\');
651          }
652          escaped.append(ch);
653        }
654        return escaped.append('"').toString();
655      }
656    
657    }