KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > suberic > pooka > FullMailcapCommandMap


1 package net.suberic.pooka;
2
3 import javax.activation.*;
4 import java.util.*;
5 import java.io.*;
6
7 /**
8  * FullMailcapCommandMap accepts both x-java-* type mailcap entries
9  * as well as standard, external-to-java entries.
10  *
11  * It uses the following resources as the sources:
12  *
13  * The file .mailcap (or mailcap.txt) in the user's home directory.
14  * The file <java.home>/lib/mailcap.
15  * The file or resource named META-INF/mailcap.
16  * The file or resource named META-INF/mailcap.default
17  * (usually found only in the activation.jar file).
18  */

19
20 public class FullMailcapCommandMap extends MailcapCommandMap {
21   private Vector mailcapMaps;
22   private static String JavaDoc externalLauncher = "net.suberic.pooka.ExternalLauncher";
23   private File sourceFile = null;;
24   
25   /**
26    * Creates a FullMailcapCommandMap.
27    */

28   public FullMailcapCommandMap() {
29     initializeMailcap(null);
30   }
31   
32   /**
33    * Create a FullMailcapCommandMap that uses the file represented by
34    * localMailcap as the top-most entry in the mailcap list.
35    */

36   public FullMailcapCommandMap(String JavaDoc localMailcap) throws java.io.IOException JavaDoc {
37     initializeMailcap(localMailcap);
38   }
39   /*
40     try {
41       if (System.getProperty("file.separator").equals("\\")) {
42     sourceFile = new File(System.getProperty("user.home") + "\\pooka_mailcap.txt");
43     addMailcapFile(System.getProperty("user.home") + "\\pooka_mailcap.txt");
44       } else {
45     sourceFile = new File(System.getProperty("user.home") + System.getProperty("file.separator") + ".pooka_mailcap");
46     addMailcapFile(System.getProperty("user.home") + System.getProperty("file.separator") + ".pooka_mailcap");
47       }
48     } catch (IOException ioe) {
49       // if it doesn't exist, it's ok.
50     }
51   */

52   
53   /**
54    * Return the DataContentHandler for the specified MIME type.
55    */

56   public DataContentHandler createDataContentHandler(java.lang.String JavaDoc mimeType) {
57     CommandInfo[] allCmds = getAllCommands(mimeType);
58     DataContentHandler returnValue = null;
59     if (allCmds != null) {
60       for (int i = 0; i < allCmds.length; i++) {
61     CommandInfo current = allCmds[i];
62     if (current != null) {
63       String JavaDoc name = current.getCommandName();
64       if (name != null && name.equalsIgnoreCase("content-handler")) {
65         try {
66           String JavaDoc className = current.getCommandClass();
67           if (returnValue == null)
68           returnValue = (DataContentHandler) Class.forName(className).newInstance();
69         } catch (Exception JavaDoc e) {
70         }
71       }
72     }
73       }
74     }
75
76     if (returnValue == null)
77       return super.createDataContentHandler(mimeType);
78     else
79       return returnValue;
80   }
81
82   /**
83    * this adds the following files/resources, in order:
84    *
85    * The file localMailcap.
86    * The file .mailcap (or mailcap.txt) in the user's home directory.
87    * The file <java.home>/lib/mailcap.
88    * The file or resource named META-INF/mailcap.
89    * The file or resource named META-INF/mailcap.default
90    * (usually found only in the activation.jar file).
91    */

92   public void initializeMailcap(String JavaDoc localMailcap) {
93     
94     mailcapMaps = new Vector();
95     
96     InputStream is;
97     
98     try {
99       if (localMailcap != null) {
100     sourceFile = new File(localMailcap);
101     
102     addMailcapFile(localMailcap);
103       }
104     } catch (IOException ioe) {
105       // if it doesn't exist, it's ok.
106
}
107     
108     try {
109       if (System.getProperty("file.separator").equals("\\")) {
110     if (sourceFile == null)
111       sourceFile = new File(System.getProperty("user.home") + "\\mailcap.txt");
112
113     addMailcapFile(System.getProperty("user.home") + "\\mailcap.txt");
114       } else {
115     if (sourceFile == null)
116       sourceFile = new File(System.getProperty("user.home") + System.getProperty("file.separator") + ".mailcap");
117
118     addMailcapFile(System.getProperty("user.home") + System.getProperty("file.separator") + ".mailcap");
119       }
120     } catch (IOException ioe) {
121       // if it doesn't exist, it's ok.
122
}
123     
124     try {
125       addMailcapFile(System.getProperty("java.home") + System.getProperty("file.separator") + "lib" + System.getProperty("file.separator") + "mailcap");
126     } catch (IOException ioe) {
127       // if it doesn't exist, it's ok.
128
}
129     
130     is = new Object JavaDoc().getClass().getResourceAsStream("/META-INF/mailcap");
131     if (is != null)
132       addMailcapFile(is);
133     
134     is = new Object JavaDoc().getClass().getResourceAsStream("/META-INF/mailcap.default");
135     if (is != null)
136       addMailcapFile(is);
137     
138   }
139   
140
141   /**
142    * Gets all of the commands associated with the given mimeType.
143    */

144   public CommandInfo[] getAllCommands(java.lang.String JavaDoc mimeType) {
145
146     /*
147      * this just goes through the list of mailcap objects stored
148      * and calls getAllCommands() on each.
149      */

150
151       Vector foundCommands = new Vector();
152       for (int i = 0; i < mailcapMaps.size() ; i++) {
153     MailcapMap mc = (MailcapMap)mailcapMaps.elementAt(i);
154     CommandInfo[] cis = mc.getAllCommands(mimeType);
155     if (cis != null)
156       for (int j = 0; j < cis.length; j++) {
157         foundCommands.add(cis[j]);
158       }
159       }
160       
161     
162     if (foundCommands.size() == 0)
163         return null;
164     
165     CommandInfo[] returnValue = new CommandInfo[foundCommands.size()];
166     for (int k = 0; k < foundCommands.size(); k++)
167         returnValue[k] = (CommandInfo)foundCommands.elementAt(k);
168
169     return returnValue;
170         
171     }
172
173     public CommandInfo getCommand(java.lang.String JavaDoc mimeType, java.lang.String JavaDoc cmdName) {
174
175     for (int i = mailcapMaps.size(); i >= 0; i--) {
176         MailcapMap mc = (MailcapMap)mailcapMaps.elementAt(i);
177         CommandInfo cis = mc.getSpecificCommand(mimeType, cmdName);
178         if (cis != null)
179         return cis;
180
181         cis = mc.getGenericCommand(mimeType, cmdName);
182         if (cis != null)
183         return cis;
184     }
185     
186     return null;
187     }
188
189     public CommandInfo[] getPreferredCommands(java.lang.String JavaDoc mimeType) {
190     return getAllCommands(mimeType);
191     }
192
193     public void addMailcap(java.lang.String JavaDoc mail_cap) {
194     MailcapMap mc = (MailcapMap)mailcapMaps.firstElement();
195     mc.addMailcapEntry(mail_cap, true);
196     if (sourceFile != null)
197         writeEntryToSourceFile(mail_cap);
198     }
199
200   /**
201    * This writes the entry to the mailcap file. Note that it actually
202    * ends up overwriting _all_ entries for that particular mime type.
203    */

204   private synchronized void writeEntryToSourceFile(String JavaDoc mail_cap) {
205     if (sourceFile != null) {
206       int semicolonIndex = mail_cap.indexOf(';');
207       if (semicolonIndex > -1) {
208     String JavaDoc mimeType = mail_cap.substring(0, semicolonIndex);
209     try {
210       if (!sourceFile.exists())
211         sourceFile.createNewFile();
212       
213       File outputFile = sourceFile.createTempFile(sourceFile.getName(), ".tmp", sourceFile.getParentFile());
214       
215       BufferedReader readSourceFile = new BufferedReader(new FileReader(sourceFile));
216       BufferedWriter writeSourceFile = new BufferedWriter(new FileWriter(outputFile));
217       String JavaDoc currentLine = readSourceFile.readLine();
218       while (currentLine != null) {
219         int equalsLoc = currentLine.indexOf(';');
220         if (equalsLoc != -1) {
221           String JavaDoc key = currentLine.substring(0, equalsLoc);
222           
223           if (!mimeType.equalsIgnoreCase(key)) {
224         writeSourceFile.write(currentLine);
225         writeSourceFile.newLine();
226           }
227         }
228         currentLine = readSourceFile.readLine();
229       }
230       
231       
232       writeSourceFile.write(mail_cap);
233       writeSourceFile.newLine();
234       
235       readSourceFile.close();
236       writeSourceFile.flush();
237       writeSourceFile.close();
238       
239       // if you don't delete the .old file first, then the
240
// rename fails under Windows.
241
String JavaDoc oldSourceName = sourceFile.getAbsolutePath() + ".old";
242       File oldSource = new File (oldSourceName);
243       if (oldSource.exists())
244         oldSource.delete();
245       
246       String JavaDoc fileName = new String JavaDoc(sourceFile.getAbsolutePath());
247       sourceFile.renameTo(oldSource);
248       outputFile.renameTo(new File(fileName));
249       oldSource.delete();
250     } catch (Exception JavaDoc e) {
251       System.out.println("caugh exception while writing source file: " + e);
252       e.printStackTrace();
253     }
254       }
255     }
256   }
257   
258     public void addMailcapFile(java.lang.String JavaDoc mailcapFileName) throws IOException {
259       FileInputStream fis = new FileInputStream(mailcapFileName);
260       addMailcapFile(fis);
261     }
262
263     public void addMailcapFile(InputStream is) {
264     InputStreamReader isr = new InputStreamReader(is);
265     BufferedReader reader = new BufferedReader(isr);
266     
267     MailcapMap map = new MailcapMap();
268
269     try {
270         String JavaDoc nextLine = reader.readLine();
271         while (nextLine != null) {
272         if (!(nextLine.startsWith("#")))
273             map.addMailcapEntry(nextLine);
274         nextLine=reader.readLine();
275         }
276        
277         mailcapMaps.add(map);
278     } catch (Exception JavaDoc e) {
279         System.out.println("an error happened." + e.getMessage());
280         e.printStackTrace();
281         
282     } finally {
283         try {
284         reader.close();
285         } catch (IOException ioe) {
286         }
287         try {
288         isr.close();
289         } catch (IOException ioe) {
290         }
291     }
292
293     }
294
295     public static String JavaDoc getExternalLauncher() {
296     return externalLauncher;
297     }
298
299     public static void setExternalLauncher(String JavaDoc newVal) {
300     externalLauncher = newVal;
301     }
302
303     private class MailcapMap {
304     // these are Hashtables of Vectors. the Vectors should all be
305
// CommandInfos.
306

307     private Hashtable specificMap;
308     private Hashtable genericMap;
309
310     MailcapMap() {
311         specificMap=new Hashtable();
312         genericMap=new Hashtable();
313     }
314
315     CommandInfo[] getAllCommands(String JavaDoc mimeType) {
316         Vector foundCommands = new Vector();
317         Vector v = (Vector)specificMap.get(mimeType);
318
319         if (v != null) {
320         for (int i = 0; i < v.size(); i++)
321             foundCommands.add(v.elementAt(i));
322         }
323         
324         v = (Vector)genericMap.get(getGenericMimeType(mimeType));
325
326         if (v != null)
327         for (int j = 0; j < v.size(); j++)
328             foundCommands.add(v.elementAt(j));
329
330         if (foundCommands.size() == 0)
331         return null;
332         
333         CommandInfo[] commandsAsArray = new CommandInfo[foundCommands.size()];
334
335         for (int i = 0; i < foundCommands.size(); i++)
336         commandsAsArray[i] = (CommandInfo)foundCommands.elementAt(i);
337         
338         return commandsAsArray;
339     }
340
341     CommandInfo getSpecificCommand(String JavaDoc mimeType, String JavaDoc verb) {
342         return getCommandFromVector((Vector)specificMap.get(mimeType), verb);
343     }
344
345     CommandInfo getGenericCommand(String JavaDoc mimeType, String JavaDoc verb) {
346         return getCommandFromVector((Vector)genericMap.get(getGenericMimeType(mimeType)), verb);
347     }
348     
349     CommandInfo getCommandFromVector(Vector v, String JavaDoc verb) {
350         if (v == null)
351         return null;
352         
353         CommandInfo ci;
354         
355         for (int i = 0; i < v.size(); i++) {
356         ci = (CommandInfo)v.elementAt(i);
357         if (matches(ci, verb))
358             return ci;
359         }
360         
361         return null;
362     }
363     
364       public void addMailcapEntry(String JavaDoc mailcapLine) {
365     addMailcapEntry(mailcapLine, false);
366       }
367       
368       synchronized void addMailcapEntry(String JavaDoc mailcapLine, boolean prepend) {
369     String JavaDoc mimeType;
370     String JavaDoc command;
371     String JavaDoc verb;
372     
373     StringTokenizer tokens = new StringTokenizer(mailcapLine, ";");
374     if (tokens.hasMoreTokens()) {
375       mimeType = stripWhiteSpace(new StringBuffer JavaDoc(tokens.nextToken()));
376       Hashtable addTable;
377       int i = mimeType.indexOf('/');
378       if (( i != -1 ) && (i != mimeType.length()-1) && (mimeType.charAt(i+1) == '*')) {
379         addTable = genericMap;
380         mimeType = mimeType.substring(0, i-1);
381       } else {
382         addTable = specificMap;
383       }
384
385       while (tokens.hasMoreTokens()) {
386         String JavaDoc[] verbClass = parseCommand(stripWhiteSpace(new StringBuffer JavaDoc(tokens.nextToken())));
387         if (verbClass != null) {
388           Vector v = (Vector)addTable.get(mimeType);
389           if (v != null) {
390         if (prepend) {
391           v.add(0, new CommandInfo(verbClass[0], verbClass[1]));
392         } else {
393           v.add(new CommandInfo(verbClass[0], verbClass[1]));
394         }
395           } else {
396         v = new Vector();
397         v.add(new CommandInfo(verbClass[0], verbClass[1]));
398         addTable.put(mimeType, v);
399           }
400         }
401       } // while
402
} // if tokens.hasMoreTokens()
403
}
404
405       /**
406        *
407        */

408       String JavaDoc getGenericMimeType(String JavaDoc original) {
409     int slash = original.indexOf('/');
410     if (slash == -1)
411       return original;
412     else
413       return original.substring(0, slash);
414       }
415
416     boolean matches (CommandInfo ci, String JavaDoc verb) {
417         return (ci.getCommandName().equals(verb));
418     }
419     
420     String JavaDoc stripWhiteSpace(StringBuffer JavaDoc sb) {
421         int i = 0;
422         if (sb.charAt(i) == ' ' || sb.charAt(i) == '\t') {
423         while (i < sb.length() && (sb.charAt(i) == ' ' || sb.charAt(i) == '\t'))
424             i++;
425         sb.delete(0, i);
426         }
427
428         i = sb.length();
429         if (i > 0 && (sb.charAt(i-1) == ' ' || sb.charAt(i-1) == '\t')) {
430         while (i > 0 && sb.charAt(i-1) == ' ' || sb.charAt(i-1) == '\t')
431             i--;
432         sb.delete(i, sb.length());
433         }
434         return sb.toString();
435     }
436
437     /**
438      * returns a 2 dimensional String, where 0 = the command
439      * verb, and 1 = the classname.
440      *
441      * if no x-java- is found, the whole string is taken to
442      * be the verb, and the class defaults to
443      * FullMailcapCommandMap.externalLauncher.
444      */

445
446     String JavaDoc[] parseCommand(String JavaDoc command) {
447         if (command == null || command.length() < 1)
448         return null;
449         if (! command.startsWith("x-java-"))
450         return new String JavaDoc[] {command, FullMailcapCommandMap.getExternalLauncher()};
451         else {
452         int equalsIndex = command.indexOf('=');
453         if (equalsIndex < 8 || equalsIndex == command.length()-1)
454             return null;
455         else return new String JavaDoc[] {command.substring(7,equalsIndex), command.substring(equalsIndex+1)};
456         }
457     }
458     
459     
460     }
461
462 }
463     
464
465
466
467
468
Popular Tags