View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.hc.core5.http;
29  
30  import java.io.Serializable;
31  import java.nio.charset.Charset;
32  import java.nio.charset.StandardCharsets;
33  import java.nio.charset.UnsupportedCharsetException;
34  import java.util.ArrayList;
35  import java.util.Collections;
36  import java.util.HashMap;
37  import java.util.LinkedHashMap;
38  import java.util.List;
39  import java.util.Map;
40  
41  import org.apache.hc.core5.annotation.Contract;
42  import org.apache.hc.core5.annotation.ThreadingBehavior;
43  import org.apache.hc.core5.http.message.BasicHeaderValueFormatter;
44  import org.apache.hc.core5.http.message.BasicHeaderValueParser;
45  import org.apache.hc.core5.http.message.BasicNameValuePair;
46  import org.apache.hc.core5.http.message.ParserCursor;
47  import org.apache.hc.core5.util.Args;
48  import org.apache.hc.core5.util.CharArrayBuffer;
49  import org.apache.hc.core5.util.TextUtils;
50  
51  /**
52   * Content type information consisting of a MIME type and an optional charset.
53   * <p>
54   * This class makes no attempts to verify validity of the MIME type.
55   * The input parameters of the {@link #create(String, String)} method, however, may not
56   * contain characters {@code <">, <;>, <,>} reserved by the HTTP specification.
57   *
58   * @since 4.2
59   */
60  @Contract(threading = ThreadingBehavior.IMMUTABLE)
61  public final class ContentType implements Serializable {
62  
63      private static final long serialVersionUID = -7768694718232371896L;
64  
65      /**
66       * Param that represent {@code charset} constant.
67       */
68      private static final String CHARSET = "charset";
69  
70      // constants
71      public static final ContentType APPLICATION_ATOM_XML = create(
72              "application/atom+xml", StandardCharsets.UTF_8);
73      public static final ContentType APPLICATION_FORM_URLENCODED = create(
74              "application/x-www-form-urlencoded", StandardCharsets.ISO_8859_1);
75      public static final ContentType APPLICATION_JSON = create(
76              "application/json", StandardCharsets.UTF_8);
77  
78      /**
79       * Public constant media type for {@code application/x-ndjson}.
80       * @since 5.1
81       */
82      public static final ContentType APPLICATION_NDJSON = create(
83              "application/x-ndjson", StandardCharsets.UTF_8);
84  
85      public static final ContentType APPLICATION_OCTET_STREAM = create(
86              "application/octet-stream", (Charset) null);
87      /**
88       * Public constant media type for {@code application/pdf}.
89       * @since 5.1
90       */
91      public static final ContentType APPLICATION_PDF = create(
92              "application/pdf", StandardCharsets.UTF_8);
93  
94      public static final ContentType APPLICATION_SOAP_XML = create(
95              "application/soap+xml", StandardCharsets.UTF_8);
96      public static final ContentType APPLICATION_SVG_XML = create(
97              "application/svg+xml", StandardCharsets.UTF_8);
98      public static final ContentType APPLICATION_XHTML_XML = create(
99              "application/xhtml+xml", StandardCharsets.UTF_8);
100     public static final ContentType APPLICATION_XML = create(
101             "application/xml", StandardCharsets.UTF_8);
102     /**
103      * Public constant media type for {@code application/problem+json}.
104      * @see <a href="https://tools.ietf.org/html/rfc7807#section-6.1">Problem Details for HTTP APIs, 6.1. application/problem+json</a>
105      * @since 5.1
106      */
107     public static final ContentType APPLICATION_PROBLEM_JSON = create(
108             "application/problem+json", StandardCharsets.UTF_8);
109     /**
110      * Public constant media type for {@code application/problem+xml}.
111      * @see <a href="https://tools.ietf.org/html/rfc7807#section-6.2">Problem Details for HTTP APIs, 6.2. application/problem+xml</a>
112      * @since 5.1
113      */
114     public static final ContentType APPLICATION_PROBLEM_XML = create(
115             "application/problem+xml", StandardCharsets.UTF_8);
116 
117     /**
118      * Public constant media type for {@code application/rss+xml}.
119      * @since 5.1
120      */
121     public static final ContentType APPLICATION_RSS_XML = create(
122             "application/rss+xml", StandardCharsets.UTF_8);
123 
124     public static final ContentType IMAGE_BMP = create(
125             "image/bmp");
126     public static final ContentType IMAGE_GIF = create(
127             "image/gif");
128     public static final ContentType IMAGE_JPEG = create(
129             "image/jpeg");
130     public static final ContentType IMAGE_PNG = create(
131             "image/png");
132     public static final ContentType IMAGE_SVG = create(
133             "image/svg+xml");
134     public static final ContentType IMAGE_TIFF = create(
135             "image/tiff");
136     public static final ContentType IMAGE_WEBP = create(
137             "image/webp");
138     public static final ContentType MULTIPART_FORM_DATA = create(
139             "multipart/form-data", StandardCharsets.ISO_8859_1);
140 
141     /**
142      * Public constant media type for {@code multipart/mixed}.
143      * @since 5.1
144      */
145     public static final ContentType MULTIPART_MIXED = create(
146             "multipart/mixed", StandardCharsets.ISO_8859_1);
147 
148     /**
149      * Public constant media type for {@code multipart/related}.
150      * @since 5.1
151      */
152     public static final ContentType MULTIPART_RELATED = create(
153             "multipart/related", StandardCharsets.ISO_8859_1);
154 
155     public static final ContentType TEXT_HTML = create(
156             "text/html", StandardCharsets.ISO_8859_1);
157 
158     /**
159      * Public constant media type for {@code text/markdown}.
160      * @since 5.1
161      */
162     public static final ContentType TEXT_MARKDOWN = create(
163             "text/markdown", StandardCharsets.UTF_8);
164 
165     public static final ContentType TEXT_PLAIN = create(
166             "text/plain", StandardCharsets.ISO_8859_1);
167     public static final ContentType TEXT_XML = create(
168             "text/xml", StandardCharsets.UTF_8);
169     /**
170      * Public constant media type for {@code text/event-stream}.
171      * @see <a href="https://www.w3.org/TR/eventsource/">Server-Sent Events W3C recommendation</a>
172      * @since 5.1
173      */
174     public static final ContentType TEXT_EVENT_STREAM = create(
175             "text/event-stream", StandardCharsets.UTF_8);
176 
177     public static final ContentType WILDCARD = create(
178             "*/*", (Charset) null);
179 
180     /**
181      * An empty immutable {@code NameValuePair} array.
182      */
183     private static final NameValuePair[] EMPTY_NAME_VALUE_PAIR_ARRAY = {};
184 
185     /**
186      * @deprecated To be removed in 6.0
187      */
188     @Deprecated
189     private static final Map<String, ContentType> CONTENT_TYPE_MAP;
190     static {
191 
192         final ContentType[] contentTypes = {
193             APPLICATION_ATOM_XML,
194             APPLICATION_FORM_URLENCODED,
195             APPLICATION_JSON,
196             APPLICATION_SVG_XML,
197             APPLICATION_XHTML_XML,
198             APPLICATION_XML,
199             IMAGE_BMP,
200             IMAGE_GIF,
201             IMAGE_JPEG,
202             IMAGE_PNG,
203             IMAGE_SVG,
204             IMAGE_TIFF,
205             IMAGE_WEBP,
206             MULTIPART_FORM_DATA,
207             TEXT_HTML,
208             TEXT_PLAIN,
209             TEXT_XML };
210         final HashMap<String, ContentType> map = new HashMap<>();
211         for (final ContentType contentType: contentTypes) {
212             map.put(contentType.getMimeType(), contentType);
213         }
214         CONTENT_TYPE_MAP = Collections.unmodifiableMap(map);
215     }
216 
217     // defaults
218     public static final ContentType DEFAULT_TEXT = TEXT_PLAIN;
219     public static final ContentType DEFAULT_BINARY = APPLICATION_OCTET_STREAM;
220 
221     private final String mimeType;
222     private final Charset charset;
223     private final NameValuePair[] params;
224 
225     ContentType(
226             final String mimeType,
227             final Charset charset) {
228         this.mimeType = mimeType;
229         this.charset = charset;
230         this.params = null;
231     }
232 
233     ContentType(
234             final String mimeType,
235             final Charset charset,
236             final NameValuePair[] params) {
237         this.mimeType = mimeType;
238         this.charset = charset;
239         this.params = params;
240     }
241 
242     public String getMimeType() {
243         return this.mimeType;
244     }
245 
246     public Charset getCharset() {
247         return this.charset;
248     }
249 
250     /**
251      * Gets this Charset if it's non-null, otherwise, return the given {@code defaultCharset}.
252      *
253      * @param defaultCharset A default Charset.
254      * @return this Charset if it's non-null, or the given {@code defaultCharset}.
255      * @since 5.2
256      */
257     public Charset getCharset(final Charset defaultCharset) {
258         return this.charset != null ? this.charset : defaultCharset;
259     }
260 
261     /**
262      * @since 4.3
263      */
264     public String getParameter(final String name) {
265         Args.notEmpty(name, "Parameter name");
266         if (this.params == null) {
267             return null;
268         }
269         for (final NameValuePair param: this.params) {
270             if (param.getName().equalsIgnoreCase(name)) {
271                 return param.getValue();
272             }
273         }
274         return null;
275     }
276 
277     /**
278      * Generates textual representation of this content type which can be used as the value
279      * of a {@code Content-Type} header.
280      */
281     @Override
282     public String toString() {
283         final CharArrayBuffer buf = new CharArrayBuffer(64);
284         buf.append(this.mimeType);
285         if (this.params != null) {
286             buf.append("; ");
287             BasicHeaderValueFormatter.INSTANCE.formatParameters(buf, this.params, false);
288         } else if (this.charset != null) {
289             buf.append("; charset=");
290             buf.append(this.charset.name());
291         }
292         return buf.toString();
293     }
294 
295     private static boolean valid(final String s) {
296         for (int i = 0; i < s.length(); i++) {
297             final char ch = s.charAt(i);
298             if (ch == '"' || ch == ',' || ch == ';') {
299                 return false;
300             }
301         }
302         return true;
303     }
304 
305     /**
306      * Creates a new instance of {@link ContentType}.
307      *
308      * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain
309      *        characters {@code <">, <;>, <,>} reserved by the HTTP specification.
310      * @param charset charset.
311      * @return content type
312      */
313     public static ContentType create(final String mimeType, final Charset charset) {
314         final String normalizedMimeType = TextUtils.toLowerCase(Args.notBlank(mimeType, "MIME type"));
315         Args.check(valid(normalizedMimeType), "MIME type may not contain reserved characters");
316         return new ContentType(normalizedMimeType, charset);
317     }
318 
319     /**
320      * Creates a new instance of {@link ContentType} without a charset.
321      *
322      * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain
323      *        characters {@code <">, <;>, <,>} reserved by the HTTP specification.
324      * @return content type
325      */
326     public static ContentType create(final String mimeType) {
327         return create(mimeType, (Charset) null);
328     }
329 
330     /**
331      * Creates a new instance of {@link ContentType}.
332      *
333      * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain
334      *        characters {@code <">, <;>, <,>} reserved by the HTTP specification.
335      * @param charset charset. It may not contain characters {@code <">, <;>, <,>} reserved by the HTTP
336      *        specification. This parameter is optional.
337      * @return content type
338      * @throws UnsupportedCharsetException Thrown when the named charset is not available in
339      * this instance of the Java virtual machine
340      */
341     public static ContentType create(
342             final String mimeType, final String charset) throws UnsupportedCharsetException {
343         return create(mimeType, !TextUtils.isBlank(charset) ? Charset.forName(charset) : null);
344     }
345 
346     private static ContentType create(final HeaderElement helem, final boolean strict) {
347         final String mimeType = helem.getName();
348         if (TextUtils.isBlank(mimeType)) {
349             return null;
350         }
351         return create(helem.getName(), helem.getParameters(), strict);
352     }
353 
354     private static ContentType create(final String mimeType, final NameValuePair[] params, final boolean strict) {
355         Charset charset = null;
356         if (params != null) {
357             for (final NameValuePair param : params) {
358                 if (param.getName().equalsIgnoreCase(CHARSET)) {
359                     final String s = param.getValue();
360                     if (!TextUtils.isBlank(s)) {
361                         try {
362                             charset = Charset.forName(s);
363                         } catch (final UnsupportedCharsetException ex) {
364                             if (strict) {
365                                 throw ex;
366                             }
367                         }
368                     }
369                     break;
370                 }
371             }
372         }
373         return new ContentType(mimeType, charset, params != null && params.length > 0 ? params : null);
374     }
375 
376     /**
377      * Creates a new instance of {@link ContentType} with the given parameters.
378      *
379      * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain
380      *        characters {@code <">, <;>, <,>} reserved by the HTTP specification.
381      * @param params parameters.
382      * @return content type
383      *
384      * @since 4.4
385      */
386     public static ContentType create(
387             final String mimeType, final NameValuePair... params) throws UnsupportedCharsetException {
388         final String type = TextUtils.toLowerCase(Args.notBlank(mimeType, "MIME type"));
389         Args.check(valid(type), "MIME type may not contain reserved characters");
390         return create(mimeType, params != null ? params.clone() : null, true);
391     }
392 
393     /**
394      * Parses textual representation of {@code Content-Type} value.
395      *
396      * @param s text
397      * @return content type {@code Content-Type} value or null.
398      * @throws UnsupportedCharsetException Thrown when the named charset is not available in
399      * this instance of the Java virtual machine
400      */
401     public static ContentType parse(final CharSequence s) throws UnsupportedCharsetException {
402         return parse(s, true);
403     }
404 
405     /**
406      * Parses textual representation of {@code Content-Type} value ignoring invalid charsets.
407      *
408      * @param s text
409      * @return content type {@code Content-Type} value or null.
410      * @throws UnsupportedCharsetException Thrown when the named charset is not available in
411      * this instance of the Java virtual machine
412      */
413     public static ContentType parseLenient(final CharSequence s) throws UnsupportedCharsetException {
414         return parse(s, false);
415     }
416 
417     private static ContentType parse(final CharSequence s, final boolean strict) throws UnsupportedCharsetException {
418         if (TextUtils.isBlank(s)) {
419             return null;
420         }
421         final ParserCursor cursor = new ParserCursor(0, s.length());
422         final HeaderElement[] elements = BasicHeaderValueParser.INSTANCE.parseElements(s, cursor);
423         if (elements.length > 0) {
424             return create(elements[0], strict);
425         }
426         return null;
427     }
428 
429     /**
430      * Returns {@code Content-Type} for the given MIME type.
431      *
432      * @param mimeType MIME type
433      * @return content type or {@code null} if not known.
434      *
435      * @since 4.5
436      *
437      * @deprecated Do not use. This method was made public by mistake.
438      */
439     @Deprecated
440     public static ContentType getByMimeType(final String mimeType) {
441         if (mimeType == null) {
442             return null;
443         }
444         return CONTENT_TYPE_MAP.get(mimeType);
445     }
446 
447     /**
448      * Gets a ContentType's Charset if neither are null, otherwise, return the given {@code defaultCharset}.
449      *
450      * @param contentType the ContentType to test and query.
451      * @param defaultCharset a default Charset.
452      * @return the ContentType's Charset if neither are null, otherwise, return the given {@code defaultCharset}.
453      * @since 5.2
454      */
455     public static Charset getCharset(final ContentType contentType, final Charset defaultCharset) {
456         return contentType != null ? contentType.getCharset(defaultCharset) : defaultCharset;
457     }
458 
459     /**
460      * Creates a new instance with this MIME type and the given Charset.
461      *
462      * @param charset charset
463      * @return a new instance with this MIME type and the given Charset.
464      * @since 4.3
465      */
466     public ContentType withCharset(final Charset charset) {
467         return create(this.getMimeType(), charset);
468     }
469 
470     /**
471      * Creates a new instance with this MIME type and the given Charset name.
472      *
473      * @param charset name
474      * @return a new instance with this MIME type and the given Charset name.
475      * @throws UnsupportedCharsetException Thrown when the named charset is not available in
476      * this instance of the Java virtual machine
477      * @since 4.3
478      */
479     public ContentType withCharset(final String charset) {
480         return create(this.getMimeType(), charset);
481     }
482 
483     /**
484      * Creates a new instance with this MIME type and the given parameters.
485      *
486      * @param params parameters.
487      * @return a new instance with this MIME type and the given parameters.
488      * @since 4.4
489      */
490     public ContentType withParameters(
491             final NameValuePair... params) throws UnsupportedCharsetException {
492         if (params.length == 0) {
493             return this;
494         }
495         final Map<String, String> paramMap = new LinkedHashMap<>();
496         if (this.params != null) {
497             for (final NameValuePair param: this.params) {
498                 paramMap.put(param.getName(), param.getValue());
499             }
500         }
501         for (final NameValuePair param: params) {
502             paramMap.put(param.getName(), param.getValue());
503         }
504         final List<NameValuePair> newParams = new ArrayList<>(paramMap.size() + 1);
505         if (this.charset != null && !paramMap.containsKey(CHARSET)) {
506             newParams.add(new BasicNameValuePair(CHARSET, this.charset.name()));
507         }
508         for (final Map.Entry<String, String> entry: paramMap.entrySet()) {
509             newParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
510         }
511         return create(this.getMimeType(), newParams.toArray(EMPTY_NAME_VALUE_PAIR_ARRAY), true);
512     }
513 
514     public boolean isSameMimeType(final ContentType contentType) {
515         return contentType != null && mimeType.equalsIgnoreCase(contentType.getMimeType());
516     }
517 
518 }