MimeUtils.java revision 7b3ebefcdf79a251cf2a5619dd2354952fc67665
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package libcore.net;
18
19import java.io.File;
20import java.io.FileInputStream;
21import java.io.IOException;
22import java.io.InputStream;
23import java.security.AccessController;
24import java.security.PrivilegedAction;
25import java.util.HashMap;
26import java.util.Map;
27import java.util.Properties;
28
29/**
30 * Utilities for dealing with MIME types.
31 * Used to implement java.net.URLConnection and android.webkit.MimeTypeMap.
32 */
33public final class MimeUtils {
34    private static final Map<String, String> mimeTypeToExtensionMap = new HashMap<String, String>();
35
36    private static final Map<String, String> extensionToMimeTypeMap = new HashMap<String, String>();
37
38    static {
39        // The following table is based on /etc/mime.types data minus
40        // chemical/* MIME types and MIME types that don't map to any
41        // file extensions. We also exclude top-level domain names to
42        // deal with cases like:
43        //
44        // mail.google.com/a/google.com
45        //
46        // and "active" MIME types (due to potential security issues).
47
48        add("application/andrew-inset", "ez");
49        add("application/dsptype", "tsp");
50        add("application/futuresplash", "spl");
51        add("application/hta", "hta");
52        add("application/mac-binhex40", "hqx");
53        add("application/mac-compactpro", "cpt");
54        add("application/mathematica", "nb");
55        add("application/msaccess", "mdb");
56        add("application/oda", "oda");
57        add("application/ogg", "ogg");
58        add("application/pdf", "pdf");
59        add("application/pgp-keys", "key");
60        add("application/pgp-signature", "pgp");
61        add("application/pics-rules", "prf");
62        add("application/rar", "rar");
63        add("application/rdf+xml", "rdf");
64        add("application/rss+xml", "rss");
65        add("application/zip", "zip");
66        add("application/vnd.android.package-archive", "apk");
67        add("application/vnd.cinderella", "cdy");
68        add("application/vnd.ms-pki.stl", "stl");
69        add("application/vnd.oasis.opendocument.database", "odb");
70        add("application/vnd.oasis.opendocument.formula", "odf");
71        add("application/vnd.oasis.opendocument.graphics", "odg");
72        add("application/vnd.oasis.opendocument.graphics-template", "otg");
73        add("application/vnd.oasis.opendocument.image", "odi");
74        add("application/vnd.oasis.opendocument.spreadsheet", "ods");
75        add("application/vnd.oasis.opendocument.spreadsheet-template", "ots");
76        add("application/vnd.oasis.opendocument.text", "odt");
77        add("application/vnd.oasis.opendocument.text-master", "odm");
78        add("application/vnd.oasis.opendocument.text-template", "ott");
79        add("application/vnd.oasis.opendocument.text-web", "oth");
80        add("application/msword", "doc");
81        add("application/msword", "dot");
82        add("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx");
83        add("application/vnd.openxmlformats-officedocument.wordprocessingml.template", "dotx");
84        add("application/vnd.ms-excel", "xls");
85        add("application/vnd.ms-excel", "xlt");
86        add("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx");
87        add("application/vnd.openxmlformats-officedocument.spreadsheetml.template", "xltx");
88        add("application/vnd.ms-powerpoint", "ppt");
89        add("application/vnd.ms-powerpoint", "pot");
90        add("application/vnd.ms-powerpoint", "pps");
91        add("application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx");
92        add("application/vnd.openxmlformats-officedocument.presentationml.template", "potx");
93        add("application/vnd.openxmlformats-officedocument.presentationml.slideshow", "ppsx");
94        add("application/vnd.rim.cod", "cod");
95        add("application/vnd.smaf", "mmf");
96        add("application/vnd.stardivision.calc", "sdc");
97        add("application/vnd.stardivision.draw", "sda");
98        add("application/vnd.stardivision.impress", "sdd");
99        add("application/vnd.stardivision.impress", "sdp");
100        add("application/vnd.stardivision.math", "smf");
101        add("application/vnd.stardivision.writer", "sdw");
102        add("application/vnd.stardivision.writer", "vor");
103        add("application/vnd.stardivision.writer-global", "sgl");
104        add("application/vnd.sun.xml.calc", "sxc");
105        add("application/vnd.sun.xml.calc.template", "stc");
106        add("application/vnd.sun.xml.draw", "sxd");
107        add("application/vnd.sun.xml.draw.template", "std");
108        add("application/vnd.sun.xml.impress", "sxi");
109        add("application/vnd.sun.xml.impress.template", "sti");
110        add("application/vnd.sun.xml.math", "sxm");
111        add("application/vnd.sun.xml.writer", "sxw");
112        add("application/vnd.sun.xml.writer.global", "sxg");
113        add("application/vnd.sun.xml.writer.template", "stw");
114        add("application/vnd.visio", "vsd");
115        add("application/x-abiword", "abw");
116        add("application/x-apple-diskimage", "dmg");
117        add("application/x-bcpio", "bcpio");
118        add("application/x-bittorrent", "torrent");
119        add("application/x-cdf", "cdf");
120        add("application/x-cdlink", "vcd");
121        add("application/x-chess-pgn", "pgn");
122        add("application/x-cpio", "cpio");
123        add("application/x-debian-package", "deb");
124        add("application/x-debian-package", "udeb");
125        add("application/x-director", "dcr");
126        add("application/x-director", "dir");
127        add("application/x-director", "dxr");
128        add("application/x-dms", "dms");
129        add("application/x-doom", "wad");
130        add("application/x-dvi", "dvi");
131        add("application/x-flac", "flac");
132        add("application/x-font", "pfa");
133        add("application/x-font", "pfb");
134        add("application/x-font", "gsf");
135        add("application/x-font", "pcf");
136        add("application/x-font", "pcf.Z");
137        add("application/x-freemind", "mm");
138        add("application/x-futuresplash", "spl");
139        add("application/x-gnumeric", "gnumeric");
140        add("application/x-go-sgf", "sgf");
141        add("application/x-graphing-calculator", "gcf");
142        add("application/x-gtar", "gtar");
143        add("application/x-gtar", "tgz");
144        add("application/x-gtar", "taz");
145        add("application/x-hdf", "hdf");
146        add("application/x-ica", "ica");
147        add("application/x-internet-signup", "ins");
148        add("application/x-internet-signup", "isp");
149        add("application/x-iphone", "iii");
150        add("application/x-iso9660-image", "iso");
151        add("application/x-jmol", "jmz");
152        add("application/x-kchart", "chrt");
153        add("application/x-killustrator", "kil");
154        add("application/x-koan", "skp");
155        add("application/x-koan", "skd");
156        add("application/x-koan", "skt");
157        add("application/x-koan", "skm");
158        add("application/x-kpresenter", "kpr");
159        add("application/x-kpresenter", "kpt");
160        add("application/x-kspread", "ksp");
161        add("application/x-kword", "kwd");
162        add("application/x-kword", "kwt");
163        add("application/x-latex", "latex");
164        add("application/x-lha", "lha");
165        add("application/x-lzh", "lzh");
166        add("application/x-lzx", "lzx");
167        add("application/x-maker", "frm");
168        add("application/x-maker", "maker");
169        add("application/x-maker", "frame");
170        add("application/x-maker", "fb");
171        add("application/x-maker", "book");
172        add("application/x-maker", "fbdoc");
173        add("application/x-mif", "mif");
174        add("application/x-ms-wmd", "wmd");
175        add("application/x-ms-wmz", "wmz");
176        add("application/x-msi", "msi");
177        add("application/x-ns-proxy-autoconfig", "pac");
178        add("application/x-nwc", "nwc");
179        add("application/x-object", "o");
180        add("application/x-oz-application", "oza");
181        add("application/x-pkcs12", "p12");
182        add("application/x-pkcs7-certreqresp", "p7r");
183        add("application/x-pkcs7-crl", "crl");
184        add("application/x-quicktimeplayer", "qtl");
185        add("application/x-shar", "shar");
186        add("application/x-shockwave-flash", "swf");
187        add("application/x-stuffit", "sit");
188        add("application/x-sv4cpio", "sv4cpio");
189        add("application/x-sv4crc", "sv4crc");
190        add("application/x-tar", "tar");
191        add("application/x-texinfo", "texinfo");
192        add("application/x-texinfo", "texi");
193        add("application/x-troff", "t");
194        add("application/x-troff", "roff");
195        add("application/x-troff-man", "man");
196        add("application/x-ustar", "ustar");
197        add("application/x-wais-source", "src");
198        add("application/x-wingz", "wz");
199        add("application/x-webarchive", "webarchive");
200        add("application/x-webarchive-xml", "webarchivexml");
201        add("application/x-x509-ca-cert", "crt");
202        add("application/x-x509-user-cert", "crt");
203        add("application/x-xcf", "xcf");
204        add("application/x-xfig", "fig");
205        add("application/xhtml+xml", "xhtml");
206        add("audio/3gpp", "3gpp");
207        add("audio/amr", "amr");
208        add("audio/basic", "snd");
209        add("audio/midi", "mid");
210        add("audio/midi", "midi");
211        add("audio/midi", "kar");
212        add("audio/midi", "xmf");
213        add("audio/mobile-xmf", "mxmf");
214        add("audio/mpeg", "mpga");
215        add("audio/mpeg", "mpega");
216        add("audio/mpeg", "mp2");
217        add("audio/mpeg", "mp3");
218        add("audio/mpeg", "m4a");
219        add("audio/mpegurl", "m3u");
220        add("audio/prs.sid", "sid");
221        add("audio/x-aiff", "aif");
222        add("audio/x-aiff", "aiff");
223        add("audio/x-aiff", "aifc");
224        add("audio/x-gsm", "gsm");
225        add("audio/x-mpegurl", "m3u");
226        add("audio/x-ms-wma", "wma");
227        add("audio/x-ms-wax", "wax");
228        add("audio/x-pn-realaudio", "ra");
229        add("audio/x-pn-realaudio", "rm");
230        add("audio/x-pn-realaudio", "ram");
231        add("audio/x-realaudio", "ra");
232        add("audio/x-scpls", "pls");
233        add("audio/x-sd2", "sd2");
234        add("audio/x-wav", "wav");
235        add("image/bmp", "bmp");
236        add("image/gif", "gif");
237        add("image/ico", "cur");
238        add("image/ico", "ico");
239        add("image/ief", "ief");
240        add("image/jpeg", "jpeg");
241        add("image/jpeg", "jpg");
242        add("image/jpeg", "jpe");
243        add("image/pcx", "pcx");
244        add("image/png", "png");
245        add("image/svg+xml", "svg");
246        add("image/svg+xml", "svgz");
247        add("image/tiff", "tiff");
248        add("image/tiff", "tif");
249        add("image/vnd.djvu", "djvu");
250        add("image/vnd.djvu", "djv");
251        add("image/vnd.wap.wbmp", "wbmp");
252        add("image/x-cmu-raster", "ras");
253        add("image/x-coreldraw", "cdr");
254        add("image/x-coreldrawpattern", "pat");
255        add("image/x-coreldrawtemplate", "cdt");
256        add("image/x-corelphotopaint", "cpt");
257        add("image/x-icon", "ico");
258        add("image/x-jg", "art");
259        add("image/x-jng", "jng");
260        add("image/x-ms-bmp", "bmp");
261        add("image/x-photoshop", "psd");
262        add("image/x-portable-anymap", "pnm");
263        add("image/x-portable-bitmap", "pbm");
264        add("image/x-portable-graymap", "pgm");
265        add("image/x-portable-pixmap", "ppm");
266        add("image/x-rgb", "rgb");
267        add("image/x-xbitmap", "xbm");
268        add("image/x-xpixmap", "xpm");
269        add("image/x-xwindowdump", "xwd");
270        add("model/iges", "igs");
271        add("model/iges", "iges");
272        add("model/mesh", "msh");
273        add("model/mesh", "mesh");
274        add("model/mesh", "silo");
275        add("text/calendar", "ics");
276        add("text/calendar", "icz");
277        add("text/comma-separated-values", "csv");
278        add("text/css", "css");
279        add("text/html", "htm");
280        add("text/html", "html");
281        add("text/h323", "323");
282        add("text/iuls", "uls");
283        add("text/mathml", "mml");
284        // add ".txt" first so it will be the default for ExtensionFromMimeType
285        add("text/plain", "txt");
286        add("text/plain", "asc");
287        add("text/plain", "text");
288        add("text/plain", "diff");
289        add("text/plain", "po");     // reserve "pot" for vnd.ms-powerpoint
290        add("text/richtext", "rtx");
291        add("text/rtf", "rtf");
292        add("text/texmacs", "ts");
293        add("text/text", "phps");
294        add("text/tab-separated-values", "tsv");
295        add("text/xml", "xml");
296        add("text/x-bibtex", "bib");
297        add("text/x-boo", "boo");
298        add("text/x-c++hdr", "h++");
299        add("text/x-c++hdr", "hpp");
300        add("text/x-c++hdr", "hxx");
301        add("text/x-c++hdr", "hh");
302        add("text/x-c++src", "c++");
303        add("text/x-c++src", "cpp");
304        add("text/x-c++src", "cxx");
305        add("text/x-chdr", "h");
306        add("text/x-component", "htc");
307        add("text/x-csh", "csh");
308        add("text/x-csrc", "c");
309        add("text/x-dsrc", "d");
310        add("text/x-haskell", "hs");
311        add("text/x-java", "java");
312        add("text/x-literate-haskell", "lhs");
313        add("text/x-moc", "moc");
314        add("text/x-pascal", "p");
315        add("text/x-pascal", "pas");
316        add("text/x-pcs-gcd", "gcd");
317        add("text/x-setext", "etx");
318        add("text/x-tcl", "tcl");
319        add("text/x-tex", "tex");
320        add("text/x-tex", "ltx");
321        add("text/x-tex", "sty");
322        add("text/x-tex", "cls");
323        add("text/x-vcalendar", "vcs");
324        add("text/x-vcard", "vcf");
325        add("video/3gpp", "3gpp");
326        add("video/3gpp", "3gp");
327        add("video/3gpp", "3g2");
328        add("video/dl", "dl");
329        add("video/dv", "dif");
330        add("video/dv", "dv");
331        add("video/fli", "fli");
332        add("video/m4v", "m4v");
333        add("video/mpeg", "mpeg");
334        add("video/mpeg", "mpg");
335        add("video/mpeg", "mpe");
336        add("video/mp4", "mp4");
337        add("video/mpeg", "VOB");
338        add("video/quicktime", "qt");
339        add("video/quicktime", "mov");
340        add("video/vnd.mpegurl", "mxu");
341        add("video/x-la-asf", "lsf");
342        add("video/x-la-asf", "lsx");
343        add("video/x-mng", "mng");
344        add("video/x-ms-asf", "asf");
345        add("video/x-ms-asf", "asx");
346        add("video/x-ms-wm", "wm");
347        add("video/x-ms-wmv", "wmv");
348        add("video/x-ms-wmx", "wmx");
349        add("video/x-ms-wvx", "wvx");
350        add("video/x-msvideo", "avi");
351        add("video/x-sgi-movie", "movie");
352        add("x-conference/x-cooltalk", "ice");
353        add("x-epoc/x-sisx-app", "sisx");
354        applyOverrides();
355    }
356
357    private static void add(String mimeType, String extension) {
358        //
359        // if we have an existing x --> y mapping, we do not want to
360        // override it with another mapping x --> ?
361        // this is mostly because of the way the mime-type map below
362        // is constructed (if a mime type maps to several extensions
363        // the first extension is considered the most popular and is
364        // added first; we do not want to overwrite it later).
365        //
366        if (!mimeTypeToExtensionMap.containsKey(mimeType)) {
367            mimeTypeToExtensionMap.put(mimeType, extension);
368        }
369        extensionToMimeTypeMap.put(extension, mimeType);
370    }
371
372    /**
373     * This isn't what the RI does. The RI doesn't have hard-coded defaults, so supplying your
374     * own "content.types.user.table" means you don't get any of the built-ins, and the built-ins
375     * come from "$JAVA_HOME/lib/content-types.properties".
376     */
377    private static void applyOverrides() {
378        // Get the appropriate InputStream to read overrides from, if any.
379        InputStream stream = AccessController.doPrivileged(new PrivilegedAction<InputStream>() {
380            public InputStream run() {
381                // User override?
382                String userTable = System.getProperty("content.types.user.table");
383                if (userTable != null) {
384                    File f = new File(userTable);
385                    if (f.exists()) {
386                        try {
387                            return new FileInputStream(f);
388                        } catch (IOException ignored) {
389                        }
390                    }
391                }
392
393                // Standard location?
394                File f = new File(System.getProperty("java.home"),
395                        "lib" + File.separator + "content-types.properties");
396                if (f.exists()) {
397                    try {
398                        return new FileInputStream(f);
399                    } catch (IOException ignored) {
400                    }
401                }
402
403                return null;
404            }
405        });
406
407        if (stream == null) {
408            return;
409        }
410
411        try {
412            try {
413                // Read the properties file...
414                Properties overrides = new Properties();
415                overrides.load(stream);
416                // And translate its mapping to ours...
417                for (Map.Entry<Object, Object> entry : overrides.entrySet()) {
418                    String extension = (String) entry.getKey();
419                    String mimeType = (String) entry.getValue();
420                    add(mimeType, extension);
421                }
422            } finally {
423                stream.close();
424            }
425        } catch (IOException ignored) {
426        }
427    }
428
429    private MimeUtils() {
430    }
431
432    /**
433     * Returns true if the given MIME type has an entry in the map.
434     * @param mimeType A MIME type (i.e. text/plain)
435     * @return True iff there is a mimeType entry in the map.
436     */
437    public static boolean hasMimeType(String mimeType) {
438        if (mimeType == null || mimeType.isEmpty()) {
439            return false;
440        }
441        return mimeTypeToExtensionMap.containsKey(mimeType);
442    }
443
444    /**
445     * Returns the MIME type for the given extension.
446     * @param extension A file extension without the leading '.'
447     * @return The MIME type for the given extension or null iff there is none.
448     */
449    public static String guessMimeTypeFromExtension(String extension) {
450        if (extension == null || extension.isEmpty()) {
451            return null;
452        }
453        return extensionToMimeTypeMap.get(extension);
454    }
455
456    /**
457     * Returns true if the given extension has a registered MIME type.
458     * @param extension A file extension without the leading '.'
459     * @return True iff there is an extension entry in the map.
460     */
461    public static boolean hasExtension(String extension) {
462        if (extension == null || extension.isEmpty()) {
463            return false;
464        }
465        return extensionToMimeTypeMap.containsKey(extension);
466    }
467
468    /**
469     * Returns the registered extension for the given MIME type. Note that some
470     * MIME types map to multiple extensions. This call will return the most
471     * common extension for the given MIME type.
472     * @param mimeType A MIME type (i.e. text/plain)
473     * @return The extension for the given MIME type or null iff there is none.
474     */
475    public static String guessExtensionFromMimeType(String mimeType) {
476        if (mimeType == null || mimeType.isEmpty()) {
477            return null;
478        }
479        return mimeTypeToExtensionMap.get(mimeType);
480    }
481}
482