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