KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > columba > mail > folder > command > SaveMessageBodyAsCommand


1 //The contents of this file are subject to the Mozilla Public License Version 1.1
2
//(the "License"); you may not use this file except in compliance with the
3
//License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
4
//
5
//Software distributed under the License is distributed on an "AS IS" basis,
6
//WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
7
//for the specific language governing rights and
8
//limitations under the License.
9
//
10
//The Original Code is "The Columba Project"
11
//
12
//The Initial Developers of the Original Code are Frederik Dietz and Timo Stich.
13
//Portions created by Frederik Dietz and Timo Stich are Copyright (C) 2003.
14
//
15
//All Rights Reserved.
16
package org.columba.mail.folder.command;
17
18 import java.io.ByteArrayInputStream JavaDoc;
19 import java.io.File JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.io.InputStream JavaDoc;
22 import java.nio.charset.Charset JavaDoc;
23 import java.text.DateFormat JavaDoc;
24 import java.util.ArrayList JavaDoc;
25 import java.util.Enumeration JavaDoc;
26 import java.util.List JavaDoc;
27 import java.util.logging.Logger JavaDoc;
28
29 import javax.swing.JCheckBox JavaDoc;
30 import javax.swing.JFileChooser JavaDoc;
31 import javax.swing.JOptionPane JavaDoc;
32 import javax.swing.filechooser.FileFilter JavaDoc;
33
34 import org.columba.api.command.ICommandReference;
35 import org.columba.api.command.IWorkerStatusController;
36 import org.columba.core.command.Command;
37 import org.columba.core.command.StatusObservableImpl;
38 import org.columba.core.command.Worker;
39 import org.columba.core.config.Config;
40 import org.columba.core.gui.frame.FrameManager;
41 import org.columba.core.io.DiskIO;
42 import org.columba.core.io.StreamUtils;
43 import org.columba.core.xml.XmlElement;
44 import org.columba.mail.command.IMailFolderCommandReference;
45 import org.columba.mail.config.MailConfig;
46 import org.columba.mail.folder.IMailbox;
47 import org.columba.mail.gui.message.util.DocumentParser;
48 import org.columba.mail.gui.message.viewer.AttachmentModel;
49 import org.columba.mail.parser.text.HtmlParser;
50 import org.columba.mail.util.MailResourceLoader;
51 import org.columba.ristretto.coder.Base64DecoderInputStream;
52 import org.columba.ristretto.coder.CharsetDecoderInputStream;
53 import org.columba.ristretto.coder.EncodedWord;
54 import org.columba.ristretto.coder.QuotedPrintableDecoderInputStream;
55 import org.columba.ristretto.message.BasicHeader;
56 import org.columba.ristretto.message.Header;
57 import org.columba.ristretto.message.MimeHeader;
58 import org.columba.ristretto.message.MimePart;
59 import org.columba.ristretto.message.MimeTree;
60 import org.columba.ristretto.message.StreamableMimePart;
61
62
63 /**
64  * This class is used to save a message to file either as a html file or a text
65  * file.
66  *
67  * @author Karl Peder Olesen (karlpeder), 20030611
68  */

69 public class SaveMessageBodyAsCommand extends Command {
70
71     /** JDK 1.4+ logging framework logger, used for logging. */
72     private static final Logger JavaDoc LOG = Logger.getLogger("org.columba.mail.folder.command");
73
74     /** Static field representing the system line separator */
75     private static final String JavaDoc NL = "\n";
76
77     //System.getProperty("line.separator");
78

79     /** The charset to use for decoding messages before save */
80     private Charset JavaDoc charset;
81
82     private Header header;
83
84     private MimeHeader bodyHeader;
85     private InputStream JavaDoc bodyStream;
86
87     private List JavaDoc attachments;
88
89     /**
90      * Constructor for SaveMessageBodyAsCommand. Calls super constructor and
91      * saves charset for later use
92      *
93      * @param references
94      * @param charset
95      * Charset to use for decoding messages before save
96      */

97     public SaveMessageBodyAsCommand(ICommandReference reference,
98         Charset JavaDoc charset) {
99         super(reference);
100         this.charset = charset;
101     }
102
103
104     /**
105      * This method executes the save action, i.e. it saves the selected
106      * messages to disk as either plain text or as html. <br>At the momemt no
107      * header or attachment information is saved with the message!
108      *
109      * @param worker
110      * @see org.columba.api.command.Command#execute(Worker)
111      */

112     public void execute(IWorkerStatusController worker)
113         throws Exception JavaDoc {
114         IMailFolderCommandReference r = (IMailFolderCommandReference) getReference();
115         Object JavaDoc[] uids = r.getUids(); // uid for messages to save
116
IMailbox srcFolder = (IMailbox) r.getSourceFolder();
117
118         // register for status events
119
((StatusObservableImpl) srcFolder.getObservable()).setWorker(worker);
120
121         JFileChooser JavaDoc fileChooser = new JFileChooser JavaDoc();
122
123         // save each message
124
for (int j = 0; j < uids.length; j++) {
125             Object JavaDoc uid = uids[j];
126             LOG.info("Saving UID=" + uid);
127
128             header = srcFolder.getAllHeaderFields(uid);
129             setupMessageBodyPart(uid, srcFolder,worker);
130
131             AttachmentModel attMod = new AttachmentModel();
132             attMod.setCollection(srcFolder.getMimePartTree(uid));
133
134             attachments = attMod.getDisplayedMimeParts();
135
136             // determine type of body part
137
boolean ishtml = false;
138
139             if (bodyHeader.getMimeType().getSubtype().equals("html")) {
140                 ishtml = true;
141             }
142
143             // setup filters and filename for file chooser dialog
144
ExtensionFileFilter txtFilter = new ExtensionFileFilter("txt",
145                     "Text (*.txt)");
146             ExtensionFileFilter htmlFilter = new ExtensionFileFilter("html",
147                     "Html (*.html)");
148             fileChooser.resetChoosableFileFilters();
149             fileChooser.setAcceptAllFileFilterUsed(false);
150             fileChooser.addChoosableFileFilter(txtFilter);
151             fileChooser.addChoosableFileFilter(htmlFilter);
152
153             // add check box for incl. of headers
154
JCheckBox JavaDoc inclHeaders = new JCheckBox JavaDoc(MailResourceLoader.getString(
155                         "dialog", "saveas", "save_all_headers"),
156                     getInclAllHeadersOption());
157             fileChooser.setAccessory(inclHeaders);
158
159             // setup dialog title, active filter and file name
160
String JavaDoc subject = EncodedWord.decode( header.get("Subject")).toString();
161             String JavaDoc defaultName = getValidFilename(subject,true);
162
163             if (ishtml) {
164                 fileChooser.setDialogTitle(MailResourceLoader.getString(
165                         "dialog", "saveas", "save_html_message"));
166                 fileChooser.setFileFilter(htmlFilter);
167
168                 if (defaultName.length() > 0) {
169                     fileChooser.setSelectedFile(new File JavaDoc(defaultName + "."
170                             + htmlFilter.getExtension()));
171                 }
172             } else {
173                 fileChooser.setDialogTitle(MailResourceLoader.getString(
174                         "dialog", "saveas", "save_text_message"));
175                 fileChooser.setFileFilter(txtFilter);
176
177                 if (defaultName.length() > 0) {
178                     fileChooser.setSelectedFile(new File JavaDoc(defaultName + "."
179                             + txtFilter.getExtension()));
180                 }
181             }
182
183             // show dialog
184
int res = fileChooser.showSaveDialog(null);
185
186             if (res == JFileChooser.APPROVE_OPTION) {
187                 File JavaDoc f = fileChooser.getSelectedFile();
188                 ExtensionFileFilter filter = (ExtensionFileFilter) fileChooser.getFileFilter();
189
190                 // Add default extension if no extension is given by the user
191
if (ExtensionFileFilter.getFileExtension(f) == null) {
192                     f = new File JavaDoc(f.getAbsolutePath() + "."
193                             + filter.getExtension());
194                 }
195
196                 int confirm;
197
198                 if (f.exists()) {
199                     // file exists, user needs to confirm overwrite
200
confirm = JOptionPane.showConfirmDialog(FrameManager.getInstance()
201                             .getActiveFrame(),
202                             MailResourceLoader.getString("dialog", "saveas",
203                                 "overwrite_existing_file"),
204                             MailResourceLoader.getString("dialog", "saveas",
205                                 "file_exists"), JOptionPane.YES_NO_OPTION,
206                             JOptionPane.QUESTION_MESSAGE);
207                 } else {
208                     confirm = JOptionPane.YES_OPTION;
209                 }
210
211                 if (confirm == JOptionPane.YES_OPTION) {
212                     // store whether all headers should be incl.
213
boolean incl = inclHeaders.isSelected();
214                     storeInclAllHeadersOption(incl);
215                     LOG.info("Incl. all headers: " + incl);
216
217                     // save message
218
if (filter.getExtension().equals(htmlFilter.getExtension())) {
219                         saveMsgBodyAsHtml(incl, f);
220                     } else {
221                         saveMsgBodyAsText(incl, f);
222                     }
223                 }
224             }
225         }
226
227         // end of for loop over uids to save
228
}
229
230     /**
231      * Private utility to extract a valid filename from a message subject or
232      * another string. <br>This means remove the chars: / \ : , \n \t NB: If
233      * the input string is null, an empty string is returned
234      *
235      * @param subj
236      * Message subject
237      * @param replSpaces
238      * If true, spaces are replaced by _
239      * @return A valid filename without the chars mentioned
240      */

241     private String JavaDoc getValidFilename(String JavaDoc subj, boolean replSpaces) {
242         if (subj == null) {
243             return "";
244         }
245
246         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
247
248         for (int i = 0; i < subj.length(); i++) {
249             char c = subj.charAt(i);
250
251             if ((c == '\\') || (c == '/') || (c == ':') || (c == ',')
252                     || (c == '\n') || (c == '\t') || (c == '(') || (c == ')') || (c == '[') || (c == ']')) {
253                 // dismiss char
254
} else if ((c == ' ') && (replSpaces)) {
255                 buf.append('_');
256             } else {
257                 buf.append(c);
258             }
259         }
260
261         return buf.toString();
262     }
263
264     /**
265      * Gets the value of the option "Incl. all headers"
266      *
267      * @return true if all headers should be included, else false
268      */

269     private boolean getInclAllHeadersOption() {
270         boolean defaultValue = false; // default value
271

272         XmlElement options = Config.getInstance().get("options").getElement("/options");
273
274         if (options == null) {
275             return defaultValue;
276         }
277
278         XmlElement savemsg = options.getElement("/savemsg");
279
280         if (savemsg != null) {
281             if (savemsg.getAttribute("incl_all_headers",
282                         String.valueOf(defaultValue)).equals("true")) {
283                 return true;
284             } else {
285                 return false;
286             }
287         } else {
288             return defaultValue;
289         }
290     }
291
292     /**
293      * Saves the option "Incl. all headers"
294      *
295      * @param val
296      * Value of the option (true to incl. all headers)
297      */

298     private void storeInclAllHeadersOption(boolean val) {
299         XmlElement options = Config.getInstance().get("options").getElement("/options");
300
301         if (options == null) {
302             return;
303         }
304
305         XmlElement savemsg = options.getElement("/savemsg");
306
307         if (savemsg == null) {
308             // create new
309
savemsg = new XmlElement("savemsg");
310             savemsg.addAttribute("incl_all_headers", String.valueOf(val));
311             options.addElement(savemsg);
312         } else {
313             savemsg.addAttribute("incl_all_headers", String.valueOf(val));
314         }
315     }
316
317     /**
318      * Private utility to get body part of a message. User preferences
319      * regarding html messages is used to select what to retrieve. If the body
320      * part retrieved is null, a fake one containing a simple text is returned
321      *
322      * @param uid
323      * ID of message
324      * @param srcFolder
325      * AbstractMessageFolder containing the message
326      * @param worker
327      * @return body part of message
328      */

329     private void setupMessageBodyPart(Object JavaDoc uid, IMailbox srcFolder,
330         IWorkerStatusController worker) throws Exception JavaDoc {
331         // Does the user prefer html or plain text?
332
XmlElement html = MailConfig.getInstance().getMainFrameOptionsConfig()
333                                               .getRoot().getElement("/options/html");
334
335         // Get body of message depending on user preferences
336
MimeTree mimePartTree = srcFolder.getMimePartTree(uid);
337
338         MimePart bodyPart = null;
339
340         if (Boolean.valueOf(html.getAttribute("prefer")).booleanValue()) {
341             bodyPart = mimePartTree.getFirstTextPart("html");
342         } else {
343             bodyPart = mimePartTree.getFirstTextPart("plain");
344         }
345
346         if (bodyPart == null) {
347             bodyHeader = new MimeHeader();
348             bodyStream = new ByteArrayInputStream JavaDoc(new byte[0]);
349         } else {
350             bodyHeader = bodyPart.getHeader();
351             bodyStream = srcFolder.getMimePartBodyStream(uid, bodyPart.getAddress());
352         }
353     }
354
355     /**
356      * Private utility to decode the message body with the proper charset
357      *
358      * @param bodyPart
359      * The body of the message
360      * @return Decoded message body
361      * @author Karl Peder Olesen (karlpeder), 20030601
362      */

363     private String JavaDoc getDecodedMessageBody()
364         throws IOException JavaDoc {
365         int encoding = bodyHeader.getContentTransferEncoding();
366
367         switch (encoding) {
368         case MimeHeader.QUOTED_PRINTABLE: {
369             bodyStream = new QuotedPrintableDecoderInputStream(bodyStream);
370
371             break;
372         }
373
374         case MimeHeader.BASE64: {
375             bodyStream = new Base64DecoderInputStream(bodyStream);
376
377             break;
378         }
379         }
380
381         // First determine which charset to use
382
if (charset == null) {
383             try {
384                 // get charset from message
385
charset = Charset.forName(bodyHeader.getContentParameter("charset"));
386             } catch (Exception JavaDoc ex) {
387                 // decode using default charset
388
charset = Charset.forName(System.getProperty("file.encoding"));
389             }
390         }
391
392         bodyStream = new CharsetDecoderInputStream(bodyStream, charset);
393
394         return StreamUtils.readCharacterStream(bodyStream).toString();
395     }
396
397     /**
398      * Method for saving a message body as a html file. No headers are saved
399      * with the message.
400      *
401      * @param header
402      * Message headers
403      * @param bodyPart
404      * Body of message
405      * @param attachments
406      * List of attachments as MimePart objects
407      * @param inclAllHeaders
408      * If true all (except Content-Type and Mime-Version) headers
409      * are output. If false, only a small subset is included
410      * @param file
411      * File to output to
412      */

413     private void saveMsgBodyAsHtml(boolean inclAllHeaders,
414         File JavaDoc file) throws IOException JavaDoc {
415         // decode message body with respect to charset
416
String JavaDoc decodedBody = getDecodedMessageBody();
417
418         String JavaDoc body;
419
420         if (!bodyHeader.getMimeType().getSubtype().equals("html")) {
421             try {
422                 // substitute special characters like: <,>,&,\t,\n
423
body = HtmlParser.substituteSpecialCharacters(decodedBody);
424
425                 // parse for urls / email adr. and substite with HTML-code
426
body = HtmlParser.substituteURL(body);
427                 body = HtmlParser.substituteEmailAddress(body);
428
429                 // mark quotings with special font
430
body = DocumentParser.markQuotings(body);
431             } catch (Exception JavaDoc e) {
432                 LOG.severe("Error parsing body: " + e.getMessage());
433                 body = "<em>Error parsing body!!!</em>";
434             }
435
436             // encapsulate bodytext in html-code
437
String JavaDoc css = getDefaultStyleSheet();
438             body = "<html><head>" + NL + css + NL
439                     + "<title>E-mail saved by Columba</title>" + NL
440                     + "</head><body><p class=\"bodytext\">" + NL + body + NL
441                     + "</p></body></html>";
442         } else {
443             // use body as is
444
body = HtmlParser.validateHTMLString(decodedBody);
445         }
446
447         // headers
448
String JavaDoc[][] headers = getHeadersToSave(inclAllHeaders);
449         String JavaDoc msg = insertHtmlHeaderTable(body, headers);
450
451         // save message
452
try {
453             DiskIO.saveStringInFile(file, msg);
454             LOG.fine("Html msg saved as " + file.getAbsolutePath());
455         } catch (IOException JavaDoc ioe) {
456             LOG.severe("Error saving message to file: " + ioe.getMessage());
457         }
458     }
459
460     /**
461      * Defines and returns a default stylesheet for use when text messages are
462      * saved as html. <br>This stylesheet should be the same as the one
463      * defined in TextViewer for use when displaying text messages.
464      */

465     private String JavaDoc getDefaultStyleSheet() {
466         // read configuration from options.xml file
467
XmlElement textFont = Config.getInstance().get("options").getElement("/options/gui/textfont");
468         String JavaDoc name = textFont.getAttribute("name");
469         String JavaDoc size = textFont.getAttribute("size");
470
471         // create css-stylesheet string
472
String JavaDoc css = "<style type=\"text/css\"><!-- .bodytext {font-family:\""
473             + name + "\"; font-size:\"" + size + "pt; \"}"
474             + ".quoting {color:#949494;}; --></style>";
475
476         return css;
477     }
478
479     /**
480      * Inserts a table with headers in a html message. The table is inserted
481      * just after the body tag.
482      *
483      * @param body
484      * Original message body
485      * @param headers
486      * Array with headers (keys and values)
487      * @return message body with header table inserted
488      */

489     private String JavaDoc insertHtmlHeaderTable(String JavaDoc body, String JavaDoc[][] headers) {
490         // create header table
491
StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
492         String JavaDoc csskey = "border: 1px solid black; font-size: 8pt; font-weight: bold;";
493         String JavaDoc cssval = "border: 1px solid black; font-size: 8pt;";
494         buf.append(
495             "<table style=\"background-color: #dddddd;\" cellspacing=\"0\">");
496         buf.append(NL);
497
498         for (int i = 0; i < headers[0].length; i++) {
499             // process header value
500
String JavaDoc val = headers[1][i];
501
502             try {
503                 val = HtmlParser.substituteSpecialCharactersInHeaderfields(val);
504                 val = HtmlParser.substituteURL(val);
505                 val = HtmlParser.substituteEmailAddress(val);
506             } catch (Exception JavaDoc e) {
507                 LOG.severe("Error parsing header value: " + e.getMessage());
508             }
509
510             buf.append("<tr><td style=\"" + csskey + "\">");
511             buf.append(headers[0][i]);
512             buf.append("</td>");
513             buf.append("<td style=\"" + cssval + "\">");
514             buf.append(val);
515             buf.append("</td></tr>");
516             buf.append(NL);
517         }
518
519         buf.append("</table>");
520         buf.append("<br>" + NL);
521
522         String JavaDoc headertbl = buf.toString();
523
524         // insert into message right after <body...>
525
int pos = body.toLowerCase().indexOf("<body");
526         pos = body.indexOf(">", pos);
527         pos++;
528
529         String JavaDoc msg = body.substring(0, pos) + headertbl + body.substring(pos);
530
531         return msg;
532     }
533
534     /**
535      * Method for saving a message in a text file.
536      *
537      * @param header Message headers
538      * @param bodyPart Body of message
539      * @param attachments List of attachments as MimePart objects
540      * @param inclAllHeaders If true all (except Content-Type and Mime-Version) headers
541      * are output. If false, only a small subset is included
542      * @param file File to output to
543      */

544     private void saveMsgBodyAsText(boolean inclAllHeaders,
545         File JavaDoc file) throws IOException JavaDoc {
546         //DocumentParser parser = new DocumentParser();
547
// decode message body with respect to charset
548
String JavaDoc decodedBody = getDecodedMessageBody();
549
550         String JavaDoc body;
551
552         if (bodyHeader.getMimeType().getSubtype().equals("html")) {
553             // strip tags
554
//body = parser.stripHTMLTags(decodedBody, true);
555
//body = parser.restoreSpecialCharacters(body);
556
body = HtmlParser.htmlToText(decodedBody);
557         } else {
558             // use body as is
559
body = decodedBody;
560         }
561
562         // headers
563
String JavaDoc[][] headers = getHeadersToSave(inclAllHeaders);
564         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
565
566         for (int i = 0; i < headers[0].length; i++) {
567             buf.append(headers[0][i]);
568             buf.append(": ");
569             buf.append(headers[1][i]);
570             buf.append(NL);
571         }
572
573         buf.append(NL);
574
575         // message composed of headers and body
576
String JavaDoc msg = buf.toString() + body;
577
578         // save message
579
DiskIO.saveStringInFile(file, msg);
580         LOG.fine("Text msg saved as " + file.getAbsolutePath());
581     }
582
583     /**
584      * Private utility to get headers to save. Headers are returned in a 2D
585      * array, so [0][i] is key[i] and [1][i] is value[i].
586      *
587      * @param header All message headers
588      * @param attachments Attachments, header lines with file names are added
589      * @param inclAll true if all headers except Content-Type and Mime-Version
590      * should be included
591      * @return Array of headers to include when saving
592      */

593     private String JavaDoc[][] getHeadersToSave(boolean inclAll) {
594         List JavaDoc keyList = new ArrayList JavaDoc();
595         List JavaDoc valueList = new ArrayList JavaDoc();
596         BasicHeader basicHeader = new BasicHeader(header);
597
598         String JavaDoc from = basicHeader.getFrom().toString();
599         String JavaDoc to = (basicHeader.getTo()[0]).toString();
600
601         DateFormat JavaDoc df = DateFormat.getDateTimeInstance(DateFormat.LONG,
602                 DateFormat.MEDIUM);
603         String JavaDoc date = df.format(basicHeader.getDate());
604
605         String JavaDoc subject = basicHeader.getSubject();
606
607         // loop over all headers
608
Enumeration JavaDoc keys = header.getKeys();
609
610         while (keys.hasMoreElements()) {
611             String JavaDoc key = (String JavaDoc) keys.nextElement();
612
613             if (key.equals("From")) {
614             } else if (key.equals("To")) {
615             } else if (key.equals("Subject")) {
616             } else if (key.equals("Date")) {
617                 // ignore - columba.date is used instead
618
} else if (key.startsWith("Content-")) {
619                 // ignore
620
} else if (key.equals("Mime-Version")
621                         || key.equals("MIME-Version")) {
622                 // ignore
623
} else if (key.startsWith("columba")) {
624                    // ignore
625
} else {
626                 if (inclAll) {
627                     // all headers should be included
628
keyList.add(key);
629                     valueList.add((String JavaDoc) header.get(key));
630                 }
631             }
632         }
633
634         // add from, to, date, subj so they are the last elements
635
keyList.add(MailResourceLoader.getString("header", "from"));
636         valueList.add(from);
637         keyList.add(MailResourceLoader.getString("header", "to"));
638         valueList.add(to);
639         keyList.add(MailResourceLoader.getString("header", "date"));
640         valueList.add(date);
641         keyList.add(MailResourceLoader.getString("header", "subject"));
642         valueList.add(subject);
643
644         for (int i = 0; i < attachments.size(); i++) {
645             String JavaDoc name = ((StreamableMimePart) attachments.get(i)).getHeader()
646                            .getFileName();
647
648             if (name != null) {
649                 keyList.add(MailResourceLoader.getString("header", "attachment"));
650                 valueList.add(name);
651             }
652         }
653
654         // create array and return
655
String JavaDoc[][] headerArray = new String JavaDoc[2][];
656         headerArray[0] = new String JavaDoc[keyList.size()];
657         headerArray[1] = new String JavaDoc[keyList.size()];
658
659         for (int i = 0; i < keyList.size(); i++) {
660             headerArray[0][i] = (String JavaDoc) keyList.get(i);
661             headerArray[1][i] = (String JavaDoc) valueList.get(i);
662         }
663
664         return headerArray;
665     }
666 }
667
668
669 /**
670  * Represents a file filter selecting only a given type of files. <br>
671  * Extension is used to recognize files. <br>Default file type is txt files.
672  */

673 class ExtensionFileFilter extends FileFilter JavaDoc {
674     /** extension to accept */
675     private String JavaDoc extension = "txt";
676
677     /** description of the file type */
678     private String JavaDoc description = "Text files (*.txt)";
679
680     /** Constructor setting the extension to accept and a type description */
681     public ExtensionFileFilter(String JavaDoc extension, String JavaDoc description) {
682         super();
683         this.extension = extension;
684         this.description = description;
685     }
686
687     /** Returns true if a given file is of the correct type */
688     public boolean accept(File JavaDoc f) {
689         if (f.isDirectory()) {
690             return true;
691         }
692
693         // test on extension
694
String JavaDoc ext = getFileExtension(f);
695
696         if ((ext != null) && (this.extension.toLowerCase().equals(ext))) {
697             return true;
698         } else {
699             return false;
700         }
701     }
702
703     /**
704      * Static method for extracting the extension of a filename
705      *
706      * @return f File to get extension for
707      * @return extension or null if no extension exist
708      */

709     public static String JavaDoc getFileExtension(File JavaDoc f) {
710         String JavaDoc ext = null;
711         String JavaDoc s = f.getName();
712         int i = s.lastIndexOf('.');
713
714         if ((i > 0) && (i < (s.length() - 1))) {
715             ext = s.substring(i + 1).toLowerCase();
716         }
717
718         return ext;
719     }
720
721     /** Returns the description of this filter / file type */
722     public String JavaDoc getDescription() {
723         return this.description;
724     }
725
726     /** Returns the extension used by this filter */
727     public String JavaDoc getExtension() {
728         return this.extension;
729     }
730 }
731
Popular Tags