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.Locale;
40  import java.util.Map;
41  
42  import org.apache.hc.core5.annotation.Contract;
43  import org.apache.hc.core5.annotation.ThreadingBehavior;
44  import org.apache.hc.core5.http.message.BasicHeaderValueFormatter;
45  import org.apache.hc.core5.http.message.BasicHeaderValueParser;
46  import org.apache.hc.core5.http.message.BasicNameValuePair;
47  import org.apache.hc.core5.http.message.ParserCursor;
48  import org.apache.hc.core5.util.Args;
49  import org.apache.hc.core5.util.CharArrayBuffer;
50  import org.apache.hc.core5.util.TextUtils;
51  
52  /**
53   * Content type information consisting of a MIME type and an optional charset.
54   * <p>
55   * This class makes no attempts to verify validity of the MIME type.
56   * The input parameters of the {@link #create(String, String)} method, however, may not
57   * contain characters {@code <">, <;>, <,>} reserved by the HTTP specification.
58   *
59   * @since 4.2
60   */
61  @Contract(threading = ThreadingBehavior.IMMUTABLE)
62  public final class ContentType implements Serializable {
63  
64      private static final long serialVersionUID = -7768694718232371896L;
65  
66      // constants
67      public static final ContentType APPLICATION_ATOM_XML = create(
68              "application/atom+xml", StandardCharsets.ISO_8859_1);
69      public static final ContentType APPLICATION_FORM_URLENCODED = create(
70              "application/x-www-form-urlencoded", StandardCharsets.ISO_8859_1);
71      public static final ContentType APPLICATION_JSON = create(
72              "application/json", StandardCharsets.UTF_8);
73      public static final ContentType APPLICATION_OCTET_STREAM = create(
74              "application/octet-stream", (Charset) null);
75      public static final ContentType APPLICATION_SVG_XML = create(
76              "application/svg+xml", StandardCharsets.ISO_8859_1);
77      public static final ContentType APPLICATION_XHTML_XML = create(
78              "application/xhtml+xml", StandardCharsets.ISO_8859_1);
79      public static final ContentType APPLICATION_XML = create(
80              "application/xml", StandardCharsets.ISO_8859_1);
81      public static final ContentType IMAGE_BMP = create(
82              "image/bmp");
83      public static final ContentType IMAGE_GIF= create(
84              "image/gif");
85      public static final ContentType IMAGE_JPEG = create(
86              "image/jpeg");
87      public static final ContentType IMAGE_PNG = create(
88              "image/png");
89      public static final ContentType IMAGE_SVG= create(
90              "image/svg+xml");
91      public static final ContentType IMAGE_TIFF = create(
92              "image/tiff");
93      public static final ContentType IMAGE_WEBP = create(
94              "image/webp");
95      public static final ContentType MULTIPART_FORM_DATA = create(
96              "multipart/form-data", StandardCharsets.ISO_8859_1);
97      public static final ContentType TEXT_HTML = create(
98              "text/html", StandardCharsets.ISO_8859_1);
99      public static final ContentType TEXT_PLAIN = create(
100             "text/plain", StandardCharsets.ISO_8859_1);
101     public static final ContentType TEXT_XML = create(
102             "text/xml", StandardCharsets.ISO_8859_1);
103     public static final ContentType WILDCARD = create(
104             "*/*", (Charset) null);
105 
106 
107     private static final Map<String, ContentType> CONTENT_TYPE_MAP;
108     static {
109 
110         final ContentType[] contentTypes = {
111             APPLICATION_ATOM_XML,
112             APPLICATION_FORM_URLENCODED,
113             APPLICATION_JSON,
114             APPLICATION_SVG_XML,
115             APPLICATION_XHTML_XML,
116             APPLICATION_XML,
117             IMAGE_BMP,
118             IMAGE_GIF,
119             IMAGE_JPEG,
120             IMAGE_PNG,
121             IMAGE_SVG,
122             IMAGE_TIFF,
123             IMAGE_WEBP,
124             MULTIPART_FORM_DATA,
125             TEXT_HTML,
126             TEXT_PLAIN,
127             TEXT_XML };
128         final HashMap<String, ContentType> map = new HashMap<>();
129         for (final ContentType contentType: contentTypes) {
130             map.put(contentType.getMimeType(), contentType);
131         }
132         CONTENT_TYPE_MAP = Collections.unmodifiableMap(map);
133     }
134 
135     // defaults
136     public static final ContentType DEFAULT_TEXT = TEXT_PLAIN;
137     public static final ContentType DEFAULT_BINARY = APPLICATION_OCTET_STREAM;
138 
139     private final String mimeType;
140     private final Charset charset;
141     private final NameValuePair[] params;
142 
143     ContentType(
144             final String mimeType,
145             final Charset charset) {
146         this.mimeType = mimeType;
147         this.charset = charset;
148         this.params = null;
149     }
150 
151     ContentType(
152             final String mimeType,
153             final Charset charset,
154             final NameValuePair[] params) {
155         this.mimeType = mimeType;
156         this.charset = charset;
157         this.params = params;
158     }
159 
160     public String getMimeType() {
161         return this.mimeType;
162     }
163 
164     public Charset getCharset() {
165         return this.charset;
166     }
167 
168     /**
169      * @since 4.3
170      */
171     public String getParameter(final String name) {
172         Args.notEmpty(name, "Parameter name");
173         if (this.params == null) {
174             return null;
175         }
176         for (final NameValuePair param: this.params) {
177             if (param.getName().equalsIgnoreCase(name)) {
178                 return param.getValue();
179             }
180         }
181         return null;
182     }
183 
184     /**
185      * Generates textual representation of this content type which can be used as the value
186      * of a {@code Content-Type} header.
187      */
188     @Override
189     public String toString() {
190         final CharArrayBuffer buf = new CharArrayBuffer(64);
191         buf.append(this.mimeType);
192         if (this.params != null) {
193             buf.append("; ");
194             BasicHeaderValueFormatter.INSTANCE.formatParameters(buf, this.params, false);
195         } else if (this.charset != null) {
196             buf.append("; charset=");
197             buf.append(this.charset.name());
198         }
199         return buf.toString();
200     }
201 
202     private static boolean valid(final String s) {
203         for (int i = 0; i < s.length(); i++) {
204             final char ch = s.charAt(i);
205             if (ch == '"' || ch == ',' || ch == ';') {
206                 return false;
207             }
208         }
209         return true;
210     }
211 
212     /**
213      * Creates a new instance of {@link ContentType}.
214      *
215      * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain
216      *        characters {@code <">, <;>, <,>} reserved by the HTTP specification.
217      * @param charset charset.
218      * @return content type
219      */
220     public static ContentType create(final String mimeType, final Charset charset) {
221         final String normalizedMimeType = Args.notBlank(mimeType, "MIME type").toLowerCase(Locale.ROOT);
222         Args.check(valid(normalizedMimeType), "MIME type may not contain reserved characters");
223         return new ContentType(normalizedMimeType, charset);
224     }
225 
226     /**
227      * Creates a new instance of {@link ContentType} without a charset.
228      *
229      * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain
230      *        characters {@code <">, <;>, <,>} reserved by the HTTP specification.
231      * @return content type
232      */
233     public static ContentType create(final String mimeType) {
234         return create(mimeType, (Charset) null);
235     }
236 
237     /**
238      * Creates a new instance of {@link ContentType}.
239      *
240      * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain
241      *        characters {@code <">, <;>, <,>} reserved by the HTTP specification.
242      * @param charset charset. It may not contain characters {@code <">, <;>, <,>} reserved by the HTTP
243      *        specification. This parameter is optional.
244      * @return content type
245      * @throws UnsupportedCharsetException Thrown when the named charset is not available in
246      * this instance of the Java virtual machine
247      */
248     public static ContentType create(
249             final String mimeType, final String charset) throws UnsupportedCharsetException {
250         return create(mimeType, !TextUtils.isBlank(charset) ? Charset.forName(charset) : null);
251     }
252 
253     private static ContentType create(final HeaderElement helem, final boolean strict) {
254         final String mimeType = helem.getName();
255         if (TextUtils.isBlank(mimeType)) {
256             return null;
257         }
258         return create(helem.getName(), helem.getParameters(), strict);
259     }
260 
261     private static ContentType create(final String mimeType, final NameValuePair[] params, final boolean strict) {
262         Charset charset = null;
263         if (params != null) {
264             for (final NameValuePair param : params) {
265                 if (param.getName().equalsIgnoreCase("charset")) {
266                     final String s = param.getValue();
267                     if (!TextUtils.isBlank(s)) {
268                         try {
269                             charset = Charset.forName(s);
270                         } catch (final UnsupportedCharsetException ex) {
271                             if (strict) {
272                                 throw ex;
273                             }
274                         }
275                     }
276                     break;
277                 }
278             }
279         }
280         return new ContentType(mimeType, charset, params != null && params.length > 0 ? params : null);
281     }
282 
283     /**
284      * Creates a new instance of {@link ContentType} with the given parameters.
285      *
286      * @param mimeType MIME type. It may not be {@code null} or empty. It may not contain
287      *        characters {@code <">, <;>, <,>} reserved by the HTTP specification.
288      * @param params parameters.
289      * @return content type
290      *
291      * @since 4.4
292      */
293     public static ContentType create(
294             final String mimeType, final NameValuePair... params) throws UnsupportedCharsetException {
295         final String type = Args.notBlank(mimeType, "MIME type").toLowerCase(Locale.ROOT);
296         Args.check(valid(type), "MIME type may not contain reserved characters");
297         return create(mimeType, params, true);
298     }
299 
300     /**
301      * Parses textual representation of {@code Content-Type} value.
302      *
303      * @param s text
304      * @return content type
305      * {@code Content-Type} value.
306      * @throws UnsupportedCharsetException Thrown when the named charset is not available in
307      * this instance of the Java virtual machine
308      */
309     public static ContentType parse(final CharSequence s) throws UnsupportedCharsetException {
310         return parse(s, true);
311     }
312 
313     /**
314      * Parses textual representation of {@code Content-Type} value ignoring invalid charsets.
315      *
316      * @param s text
317      * @return content type
318      * {@code Content-Type} value.
319      * @throws UnsupportedCharsetException Thrown when the named charset is not available in
320      * this instance of the Java virtual machine
321      */
322     public static ContentType parseLenient(final CharSequence s) throws UnsupportedCharsetException {
323         return parse(s, false);
324     }
325 
326     private static ContentType parse(final CharSequence s, final boolean strict) throws UnsupportedCharsetException {
327         if (TextUtils.isBlank(s)) {
328             return null;
329         }
330         final ParserCursor cursor = new ParserCursor(0, s.length());
331         final HeaderElement[] elements = BasicHeaderValueParser.INSTANCE.parseElements(s, cursor);
332         if (elements.length > 0) {
333             return create(elements[0], strict);
334         }
335         return null;
336     }
337 
338     /**
339      * Returns {@code Content-Type} for the given MIME type.
340      *
341      * @param mimeType MIME type
342      * @return content type or {@code null} if not known.
343      *
344      * @since 4.5
345      */
346     public static ContentType getByMimeType(final String mimeType) {
347         if (mimeType == null) {
348             return null;
349         }
350         return CONTENT_TYPE_MAP.get(mimeType);
351     }
352 
353     /**
354      * Creates a new instance with this MIME type and the given Charset.
355      *
356      * @param charset charset
357      * @return a new instance with this MIME type and the given Charset.
358      * @since 4.3
359      */
360     public ContentType withCharset(final Charset charset) {
361         return create(this.getMimeType(), charset);
362     }
363 
364     /**
365      * Creates a new instance with this MIME type and the given Charset name.
366      *
367      * @param charset name
368      * @return a new instance with this MIME type and the given Charset name.
369      * @throws UnsupportedCharsetException Thrown when the named charset is not available in
370      * this instance of the Java virtual machine
371      * @since 4.3
372      */
373     public ContentType withCharset(final String charset) {
374         return create(this.getMimeType(), charset);
375     }
376 
377     /**
378      * Creates a new instance with this MIME type and the given parameters.
379      *
380      * @param params
381      * @return a new instance with this MIME type and the given parameters.
382      * @since 4.4
383      */
384     public ContentType withParameters(
385             final NameValuePair... params) throws UnsupportedCharsetException {
386         if (params.length == 0) {
387             return this;
388         }
389         final Map<String, String> paramMap = new LinkedHashMap<>();
390         if (this.params != null) {
391             for (final NameValuePair param: this.params) {
392                 paramMap.put(param.getName(), param.getValue());
393             }
394         }
395         for (final NameValuePair param: params) {
396             paramMap.put(param.getName(), param.getValue());
397         }
398         final List<NameValuePair> newParams = new ArrayList<>(paramMap.size() + 1);
399         if (this.charset != null && !paramMap.containsKey("charset")) {
400             newParams.add(new BasicNameValuePair("charset", this.charset.name()));
401         }
402         for (final Map.Entry<String, String> entry: paramMap.entrySet()) {
403             newParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
404         }
405         return create(this.getMimeType(), newParams.toArray(new NameValuePair[newParams.size()]), true);
406     }
407 
408 }