KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > activation > MimetypesFileTypeMap


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the "License"). You may not use this file except
5  * in compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * glassfish/bootstrap/legal/CDDLv1.0.txt or
9  * https://glassfish.dev.java.net/public/CDDLv1.0.html.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * HEADER in each file and include the License file at
15  * glassfish/bootstrap/legal/CDDLv1.0.txt. If applicable,
16  * add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your
18  * own identifying information: Portions Copyright [yyyy]
19  * [name of copyright owner]
20  */

21
22 /*
23  * @(#)MimetypesFileTypeMap.java 1.17 05/11/16
24  *
25  * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
26  */

27
28 package javax.activation;
29
30 import java.io.*;
31 import java.net.*;
32 import java.util.*;
33 import com.sun.activation.registries.MimeTypeFile;
34 import com.sun.activation.registries.LogSupport;
35
36 /**
37  * This class extends FileTypeMap and provides data typing of files
38  * via their file extension. It uses the <code>.mime.types</code> format. <p>
39  *
40  * <b>MIME types file search order:</b><p>
41  * The MimetypesFileTypeMap looks in various places in the user's
42  * system for MIME types file entries. When requests are made
43  * to search for MIME types in the MimetypesFileTypeMap, it searches
44  * MIME types files in the following order:
45  * <p>
46  * <ol>
47  * <li> Programmatically added entries to the MimetypesFileTypeMap instance.
48  * <li> The file <code>.mime.types</code> in the user's home directory.
49  * <li> The file &lt;<i>java.home</i>&gt;<code>/lib/mime.types</code>.
50  * <li> The file or resources named <code>META-INF/mime.types</code>.
51  * <li> The file or resource named <code>META-INF/mimetypes.default</code>
52  * (usually found only in the <code>activation.jar</code> file).
53  * </ol>
54  * <p>
55  * <b>MIME types file format:</b><p>
56  *
57  * <code>
58  * # comments begin with a '#'<br>
59  * # the format is &lt;mime type> &lt;space separated file extensions><br>
60  * # for example:<br>
61  * text/plain txt text TXT<br>
62  * # this would map file.txt, file.text, and file.TXT to<br>
63  * # the mime type "text/plain"<br>
64  * </code>
65  *
66  * @author Bart Calder
67  * @author Bill Shannon
68  */

69 public class MimetypesFileTypeMap extends FileTypeMap JavaDoc {
70     /*
71      * We manage a collection of databases, searched in order.
72      * The default database is shared between all instances
73      * of this class.
74      * XXX - Can we safely share more databases between instances?
75      */

76     private static MimeTypeFile defDB = null;
77     private MimeTypeFile[] DB;
78     private static final int PROG = 0; // programmatically added entries
79

80     private static String JavaDoc defaultType = "application/octet-stream";
81
82     /**
83      * The default constructor.
84      */

85     public MimetypesFileTypeMap() {
86     Vector dbv = new Vector(5); // usually 5 or less databases
87
MimeTypeFile mf = null;
88     dbv.addElement(null); // place holder for PROG entry
89

90     LogSupport.log("MimetypesFileTypeMap: load HOME");
91     try {
92         String JavaDoc user_home = System.getProperty("user.home");
93
94         if (user_home != null) {
95         String JavaDoc path = user_home + File.separator + ".mime.types";
96         mf = loadFile(path);
97         if (mf != null)
98             dbv.addElement(mf);
99         }
100     } catch (SecurityException JavaDoc ex) {}
101
102     LogSupport.log("MimetypesFileTypeMap: load SYS");
103     try {
104         // check system's home
105
String JavaDoc system_mimetypes = System.getProperty("java.home") +
106         File.separator + "lib" + File.separator + "mime.types";
107         mf = loadFile(system_mimetypes);
108         if (mf != null)
109         dbv.addElement(mf);
110     } catch (SecurityException JavaDoc ex) {}
111
112     LogSupport.log("MimetypesFileTypeMap: load JAR");
113     // load from the app's jar file
114
loadAllResources(dbv, "META-INF/mime.types");
115
116     LogSupport.log("MimetypesFileTypeMap: load DEF");
117     synchronized (MimetypesFileTypeMap JavaDoc.class) {
118         // see if another instance has created this yet.
119
if (defDB == null)
120         defDB = loadResource("/META-INF/mimetypes.default");
121     }
122
123     if (defDB != null)
124         dbv.addElement(defDB);
125
126     DB = new MimeTypeFile[dbv.size()];
127     dbv.copyInto(DB);
128     }
129
130     /**
131      * Load from the named resource.
132      */

133     private MimeTypeFile loadResource(String JavaDoc name) {
134     InputStream clis = null;
135     try {
136         clis = SecuritySupport.getResourceAsStream(this.getClass(), name);
137         if (clis != null) {
138         MimeTypeFile mf = new MimeTypeFile(clis);
139         if (LogSupport.isLoggable())
140             LogSupport.log("MimetypesFileTypeMap: successfully " +
141             "loaded mime types file: " + name);
142         return mf;
143         } else {
144         if (LogSupport.isLoggable())
145             LogSupport.log("MimetypesFileTypeMap: not loading " +
146             "mime types file: " + name);
147         }
148     } catch (IOException e) {
149         if (LogSupport.isLoggable())
150         LogSupport.log("MimetypesFileTypeMap: can't load " + name, e);
151     } catch (SecurityException JavaDoc sex) {
152         if (LogSupport.isLoggable())
153         LogSupport.log("MimetypesFileTypeMap: can't load " + name, sex);
154     } finally {
155         try {
156         if (clis != null)
157             clis.close();
158         } catch (IOException ex) { } // ignore it
159
}
160     return null;
161     }
162
163     /**
164      * Load all of the named resource.
165      */

166     private void loadAllResources(Vector v, String JavaDoc name) {
167     boolean anyLoaded = false;
168     try {
169         URL[] urls;
170         ClassLoader JavaDoc cld = null;
171         // First try the "application's" class loader.
172
cld = SecuritySupport.getContextClassLoader();
173         if (cld == null)
174         cld = this.getClass().getClassLoader();
175         if (cld != null)
176         urls = SecuritySupport.getResources(cld, name);
177         else
178         urls = SecuritySupport.getSystemResources(name);
179         if (urls != null) {
180         if (LogSupport.isLoggable())
181             LogSupport.log("MimetypesFileTypeMap: getResources");
182         for (int i = 0; i < urls.length; i++) {
183             URL url = urls[i];
184             InputStream clis = null;
185             if (LogSupport.isLoggable())
186             LogSupport.log("MimetypesFileTypeMap: URL " + url);
187             try {
188             clis = SecuritySupport.openStream(url);
189             if (clis != null) {
190                 v.addElement(new MimeTypeFile(clis));
191                 anyLoaded = true;
192                 if (LogSupport.isLoggable())
193                 LogSupport.log("MimetypesFileTypeMap: " +
194                     "successfully loaded " +
195                     "mime types from URL: " + url);
196             } else {
197                 if (LogSupport.isLoggable())
198                 LogSupport.log("MimetypesFileTypeMap: " +
199                     "not loading " +
200                     "mime types from URL: " + url);
201             }
202             } catch (IOException ioex) {
203             if (LogSupport.isLoggable())
204                 LogSupport.log("MimetypesFileTypeMap: can't load " +
205                         url, ioex);
206             } catch (SecurityException JavaDoc sex) {
207             if (LogSupport.isLoggable())
208                 LogSupport.log("MimetypesFileTypeMap: can't load " +
209                         url, sex);
210             } finally {
211             try {
212                 if (clis != null)
213                 clis.close();
214             } catch (IOException cex) { }
215             }
216         }
217         }
218     } catch (Exception JavaDoc ex) {
219         if (LogSupport.isLoggable())
220         LogSupport.log("MimetypesFileTypeMap: can't load " + name, ex);
221     }
222
223     // if failed to load anything, fall back to old technique, just in case
224
if (!anyLoaded) {
225         LogSupport.log("MimetypesFileTypeMap: !anyLoaded");
226         MimeTypeFile mf = loadResource("/" + name);
227         if (mf != null)
228         v.addElement(mf);
229     }
230     }
231
232     /**
233      * Load the named file.
234      */

235     private MimeTypeFile loadFile(String JavaDoc name) {
236     MimeTypeFile mtf = null;
237
238     try {
239         mtf = new MimeTypeFile(name);
240     } catch (IOException e) {
241         // e.printStackTrace();
242
}
243     return mtf;
244     }
245
246     /**
247      * Construct a MimetypesFileTypeMap with programmatic entries
248      * added from the named file.
249      *
250      * @param mimeTypeFileName the file name
251      */

252     public MimetypesFileTypeMap(String JavaDoc mimeTypeFileName) throws IOException {
253     this();
254     DB[PROG] = new MimeTypeFile(mimeTypeFileName);
255     }
256
257     /**
258      * Construct a MimetypesFileTypeMap with programmatic entries
259      * added from the InputStream.
260      *
261      * @param is the input stream to read from
262      */

263     public MimetypesFileTypeMap(InputStream is) {
264     this();
265     try {
266         DB[PROG] = new MimeTypeFile(is);
267     } catch (IOException ex) {
268         // XXX - really should throw it
269
}
270     }
271
272     /**
273      * Prepend the MIME type values to the registry.
274      *
275      * @param mime_types A .mime.types formatted string of entries.
276      */

277     public synchronized void addMimeTypes(String JavaDoc mime_types) {
278     // check to see if we have created the registry
279
if (DB[PROG] == null)
280         DB[PROG] = new MimeTypeFile(); // make one
281

282     DB[PROG].appendToRegistry(mime_types);
283     }
284
285     /**
286      * Return the MIME type of the file object.
287      * The implementation in this class calls
288      * <code>getContentType(f.getName())</code>.
289      *
290      * @param f the file
291      * @return the file's MIME type
292      */

293     public String JavaDoc getContentType(File f) {
294     return this.getContentType(f.getName());
295     }
296
297     /**
298      * Return the MIME type based on the specified file name.
299      * The MIME type entries are searched as described above under
300      * <i>MIME types file search order</i>.
301      * If no entry is found, the type "application/octet-stream" is returned.
302      *
303      * @param filename the file name
304      * @return the file's MIME type
305      */

306     public synchronized String JavaDoc getContentType(String JavaDoc filename) {
307     int dot_pos = filename.lastIndexOf("."); // period index
308

309     if (dot_pos < 0)
310         return defaultType;
311
312     String JavaDoc file_ext = filename.substring(dot_pos + 1);
313     if (file_ext.length() == 0)
314         return defaultType;
315
316     for (int i = 0; i < DB.length; i++) {
317         if (DB[i] == null)
318         continue;
319         String JavaDoc result = DB[i].getMIMETypeString(file_ext);
320         if (result != null)
321         return result;
322     }
323     return defaultType;
324     }
325
326     /**
327      * for debugging...
328      *
329     public static void main(String[] argv) throws Exception {
330     MimetypesFileTypeMap map = new MimetypesFileTypeMap();
331     System.out.println("File " + argv[0] + " has MIME type " +
332                         map.getContentType(argv[0]));
333     System.exit(0);
334     }
335     */

336 }
337
Popular Tags