1
2
3
4
5
6
7 package org.astrogrid.slinger.mime ;
8
9 /***
10 * Guesses between file extensions and mime types. From filestore FileProperties.
11 *
12 */
13 import java.util.Hashtable;
14
15 public class MimeFileExts implements MimeTypes {
16
17 /***
18 * Known MIME type values.
19 */
20 private static Hashtable extLookup = null;
21 private static Hashtable mimeLookup = null;
22
23 private static void addLookup(String mime, String ext) {
24 extLookup.put(mime.trim().toLowerCase(), ext.trim().toLowerCase());
25 mimeLookup.put(ext.trim().toLowerCase(), mime.trim().toLowerCase());
26 }
27
28 /*** Populates lookup tables. There are many duplicates here as the lookup
29 * works both ways. As duplicates replace previous ones, make sure the *last*
30 * addition is the 'default'
31 */
32 public synchronized static void initialise() {
33
34 if (extLookup != null) { return; }
35
36 extLookup = new Hashtable();
37 mimeLookup = new Hashtable();
38
39
40 addLookup(PLAINTEXT, "txt");
41 addLookup(XML, "xsl");
42 addLookup(XML, "xml");
43 addLookup(VOTABLE, "vot");
44 addLookup(VOTABLE, "votable");
45 addLookup(VOLIST, "vol");
46 addLookup(VOLIST, "volist");
47 addLookup(JOB, "job");
48 addLookup(WORKFLOW, "work");
49 addLookup(WORKFLOW, "workflow");
50 addLookup(WORKFLOW, "flow");
51 addLookup(ADQL, "adql");
52 addLookup(ADQL, "query");
53 }
54
55 /***
56 * Guess the mime type from a file name.
57 * @return The mime type if the filename has a recognised .extension, otherwise null.
58 *
59 */
60 public static String guessMimeType(String filename) {
61
62 if (extLookup == null) {
63 initialise();
64 }
65
66 if (null == filename) {
67 return null;
68 }
69
70
71 int index = filename.lastIndexOf('.') ;
72
73 if (index == -1) {
74 return null;
75 }
76
77 String ext = filename.substring(index+1);
78
79 return (String) mimeLookup.get(ext.toLowerCase());
80 }
81
82 /***
83 * Guess an extension from a mime type. Returns the mimetype to the first space/slash
84 * if unknown
85 *
86 */
87 public static String guessExt(String mimeType) {
88
89 if (extLookup == null) {
90 initialise();
91 }
92
93 if (null == mimeType) {
94 return "";
95 }
96
97 String ext = (String) extLookup.get(mimeType.toLowerCase());
98
99
100 if (ext == null) {
101 if (mimeType.indexOf(' ')>-1) {
102 String mimeStem = mimeType.substring(0, ext.indexOf(' '));
103 ext = (String) extLookup.get(mimeStem.toLowerCase());
104
105 if (ext == null) {
106
107 ext = mimeStem.replaceAll("/","_");
108 }
109 }
110 }
111 return ext;
112 }
113 }
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136