1 17 package org.columba.mail.folder.mbox; 18 19 import java.io.IOException ; 20 import java.util.Iterator ; 21 import java.util.LinkedList ; 22 import java.util.List ; 23 import java.util.regex.Matcher ; 24 import java.util.regex.Pattern ; 25 26 import org.columba.ristretto.io.Source; 27 import org.columba.ristretto.parser.CharSequenceSearcher; 28 29 public class MboxParser { 30 31 private static final Pattern YEAR_DIGITS = Pattern.compile("\\d{4}$"); 32 33 public static MboxMessage[] parseMbox(Source mailboxSource) throws IOException { 34 Matcher mboxHeaderMatcher = YEAR_DIGITS.matcher(""); 35 List messages = new LinkedList (); 36 37 CharSequenceSearcher searcher = new CharSequenceSearcher("From "); 38 List boundaries = searcher.match(mailboxSource); 39 40 Iterator it = boundaries.iterator(); 41 int start = ((Integer ) it.next()).intValue(); 42 int lastEnd = findNext(mailboxSource, start + 5, '\n') + 1; 43 44 int newUid = 0; 45 46 47 while (it.hasNext()) { 48 start = ((Integer ) it.next()).intValue(); 49 50 int possibleEnd = findNext(mailboxSource, start + 5, '\n') + 1; 51 52 mboxHeaderMatcher.reset(mailboxSource.subSequence(start, possibleEnd-1)); 53 while( !mboxHeaderMatcher.find() && it.hasNext()) { 54 start = ((Integer ) it.next()).intValue(); 55 possibleEnd = findNext(mailboxSource, start + 5, '\n') + 1; 56 mboxHeaderMatcher.reset(mailboxSource.subSequence(start, possibleEnd)); 57 } 58 59 messages.add(new MboxMessage(new Integer (newUid++), lastEnd, 60 start - lastEnd)); 61 62 lastEnd = possibleEnd; 63 } 64 65 messages.add(new MboxMessage(new Integer (newUid++), lastEnd, 66 mailboxSource.length() - lastEnd)); 67 68 return (MboxMessage[]) messages.toArray(new MboxMessage[0]); 69 } 70 71 private static int findNext(Source source, int pos, char ch) { 72 pos++; 73 while (!source.isEOF()) { 74 if (source.charAt(pos) == ch) { 75 return pos; 76 } else { 77 pos++; 78 } 79 } 80 81 return -1; 82 } 83 84 } 85 | Popular Tags |