KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > activation > registries > MimeTypeFile


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  * @(#)MimeTypeFile.java 1.8 05/11/16
24  *
25  * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
26  */

27
28 package com.sun.activation.registries;
29
30 import java.io.*;
31 import java.util.*;
32
33 public class MimeTypeFile {
34     private String JavaDoc fname = null;
35     private Hashtable type_hash = new Hashtable();
36
37     /**
38      * The construtor that takes a filename as an argument.
39      *
40      * @param new_fname The file name of the mime types file.
41      */

42     public MimeTypeFile(String JavaDoc new_fname) throws IOException {
43     File mime_file = null;
44     FileReader fr = null;
45
46     fname = new_fname; // remember the file name
47

48     mime_file = new File(fname); // get a file object
49

50     fr = new FileReader(mime_file);
51
52     try {
53         parse(new BufferedReader(fr));
54     } finally {
55         try {
56         fr.close(); // close it
57
} catch (IOException e) {
58         // ignore it
59
}
60     }
61     }
62
63     public MimeTypeFile(InputStream is) throws IOException {
64     parse(new BufferedReader(new InputStreamReader(is, "iso-8859-1")));
65     }
66
67     /**
68      * Creates an empty DB.
69      */

70     public MimeTypeFile() {
71     }
72
73     /**
74      * get the MimeTypeEntry based on the file extension
75      */

76     public MimeTypeEntry getMimeTypeEntry(String JavaDoc file_ext) {
77     return (MimeTypeEntry)type_hash.get((Object JavaDoc)file_ext);
78     }
79
80     /**
81      * Get the MIME type string corresponding to the file extension.
82      */

83     public String JavaDoc getMIMETypeString(String JavaDoc file_ext) {
84     MimeTypeEntry entry = this.getMimeTypeEntry(file_ext);
85
86     if (entry != null)
87         return entry.getMIMEType();
88     else
89         return null;
90     }
91
92     /**
93      * Appends string of entries to the types registry, must be valid
94      * .mime.types format.
95      * A mime.types entry is one of two forms:
96      *
97      * type/subtype ext1 ext2 ...
98      * or
99      * type=type/subtype desc="description of type" exts=ext1,ext2,...
100      *
101      * Example:
102      * # this is a test
103      * audio/basic au
104      * text/plain txt text
105      * type=application/postscript exts=ps,eps
106      */

107     public void appendToRegistry(String JavaDoc mime_types) {
108     try {
109         parse(new BufferedReader(new StringReader(mime_types)));
110     } catch (IOException ex) {
111         // can't happen
112
}
113     }
114
115     /**
116      * Parse a stream of mime.types entries.
117      */

118     private void parse(BufferedReader buf_reader) throws IOException {
119     String JavaDoc line = null, prev = null;
120
121     while ((line = buf_reader.readLine()) != null) {
122         if (prev == null)
123         prev = line;
124         else
125         prev += line;
126         int end = prev.length();
127         if (prev.length() > 0 && prev.charAt(end - 1) == '\\') {
128         prev = prev.substring(0, end - 1);
129         continue;
130         }
131         this.parseEntry(prev);
132         prev = null;
133     }
134     if (prev != null)
135         this.parseEntry(prev);
136     }
137
138     /**
139      * Parse single mime.types entry.
140      */

141     private void parseEntry(String JavaDoc line) {
142     String JavaDoc mime_type = null;
143     String JavaDoc file_ext = null;
144     line = line.trim();
145
146     if (line.length() == 0) // empty line...
147
return; // BAIL!
148

149     // check to see if this is a comment line?
150
if (line.charAt(0) == '#')
151         return; // then we are done!
152

153     // is it a new format line or old format?
154
if (line.indexOf('=') > 0) {
155         // new format
156
LineTokenizer lt = new LineTokenizer(line);
157         while (lt.hasMoreTokens()) {
158         String JavaDoc name = lt.nextToken();
159         String JavaDoc value = null;
160         if (lt.hasMoreTokens() && lt.nextToken().equals("=") &&
161                             lt.hasMoreTokens())
162             value = lt.nextToken();
163         if (value == null) {
164             if (LogSupport.isLoggable())
165             LogSupport.log("Bad .mime.types entry: " + line);
166             return;
167         }
168         if (name.equals("type"))
169             mime_type = value;
170         else if (name.equals("exts")) {
171             StringTokenizer st = new StringTokenizer(value, ",");
172             while (st.hasMoreTokens()) {
173             file_ext = st.nextToken();
174             MimeTypeEntry entry =
175                 new MimeTypeEntry(mime_type, file_ext);
176             type_hash.put(file_ext, entry);
177             if (LogSupport.isLoggable())
178                 LogSupport.log("Added: " + entry.toString());
179             }
180         }
181         }
182     } else {
183         // old format
184
// count the tokens
185
StringTokenizer strtok = new StringTokenizer(line);
186         int num_tok = strtok.countTokens();
187
188         if (num_tok == 0) // empty line
189
return;
190
191         mime_type = strtok.nextToken(); // get the MIME type
192

193         while (strtok.hasMoreTokens()) {
194         MimeTypeEntry entry = null;
195
196         file_ext = strtok.nextToken();
197         entry = new MimeTypeEntry(mime_type, file_ext);
198         type_hash.put(file_ext, entry);
199         if (LogSupport.isLoggable())
200             LogSupport.log("Added: " + entry.toString());
201         }
202     }
203     }
204
205     // for debugging
206
/*
207     public static void main(String[] argv) throws Exception {
208     MimeTypeFile mf = new MimeTypeFile(argv[0]);
209     System.out.println("ext " + argv[1] + " type " +
210                         mf.getMIMETypeString(argv[1]));
211     System.exit(0);
212     }
213     */

214 }
215
216 class LineTokenizer {
217     private int currentPosition;
218     private int maxPosition;
219     private String JavaDoc str;
220     private Vector stack = new Vector();
221     private static final String JavaDoc singles = "="; // single character tokens
222

223     /**
224      * Constructs a tokenizer for the specified string.
225      * <p>
226      *
227      * @param str a string to be parsed.
228      */

229     public LineTokenizer(String JavaDoc str) {
230     currentPosition = 0;
231     this.str = str;
232     maxPosition = str.length();
233     }
234
235     /**
236      * Skips white space.
237      */

238     private void skipWhiteSpace() {
239     while ((currentPosition < maxPosition) &&
240            Character.isWhitespace(str.charAt(currentPosition))) {
241         currentPosition++;
242     }
243     }
244
245     /**
246      * Tests if there are more tokens available from this tokenizer's string.
247      *
248      * @return <code>true</code> if there are more tokens available from this
249      * tokenizer's string; <code>false</code> otherwise.
250      */

251     public boolean hasMoreTokens() {
252     if (stack.size() > 0)
253         return true;
254     skipWhiteSpace();
255     return (currentPosition < maxPosition);
256     }
257
258     /**
259      * Returns the next token from this tokenizer.
260      *
261      * @return the next token from this tokenizer.
262      * @exception NoSuchElementException if there are no more tokens in this
263      * tokenizer's string.
264      */

265     public String JavaDoc nextToken() {
266     int size = stack.size();
267     if (size > 0) {
268         String JavaDoc t = (String JavaDoc)stack.elementAt(size - 1);
269         stack.removeElementAt(size - 1);
270         return t;
271     }
272     skipWhiteSpace();
273
274     if (currentPosition >= maxPosition) {
275         throw new NoSuchElementException();
276     }
277
278     int start = currentPosition;
279     char c = str.charAt(start);
280     if (c == '"') {
281         currentPosition++;
282         boolean filter = false;
283         while (currentPosition < maxPosition) {
284         c = str.charAt(currentPosition++);
285         if (c == '\\') {
286             currentPosition++;
287             filter = true;
288         } else if (c == '"') {
289             String JavaDoc s;
290
291             if (filter) {
292             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
293             for (int i = start + 1; i < currentPosition - 1; i++) {
294                 c = str.charAt(i);
295                 if (c != '\\')
296                 sb.append(c);
297             }
298             s = sb.toString();
299             } else
300             s = str.substring(start + 1, currentPosition - 1);
301             return s;
302         }
303         }
304     } else if (singles.indexOf(c) >= 0) {
305         currentPosition++;
306     } else {
307         while ((currentPosition < maxPosition) &&
308            singles.indexOf(str.charAt(currentPosition)) < 0 &&
309            !Character.isWhitespace(str.charAt(currentPosition))) {
310         currentPosition++;
311         }
312     }
313     return str.substring(start, currentPosition);
314     }
315
316     public void pushToken(String JavaDoc token) {
317     stack.addElement(token);
318     }
319 }
320
Popular Tags