01: //The contents of this file are subject to the Mozilla Public License Version 1.1
02: //(the "License"); you may not use this file except in compliance with the
03: //License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
04: //
05: //Software distributed under the License is distributed on an "AS IS" basis,
06: //WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
07: //for the specific language governing rights and
08: //limitations under the License.
09: //
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:
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
32: .compile("\\d{4}$");
33:
34: public static MboxMessage[] parseMbox(Source mailboxSource)
35: throws IOException {
36: Matcher mboxHeaderMatcher = YEAR_DIGITS.matcher("");
37: List messages = new LinkedList();
38:
39: CharSequenceSearcher searcher = new CharSequenceSearcher(
40: "From ");
41: List boundaries = searcher.match(mailboxSource);
42:
43: Iterator it = boundaries.iterator();
44: int start = ((Integer) it.next()).intValue();
45: int lastEnd = findNext(mailboxSource, start + 5, '\n') + 1;
46:
47: int newUid = 0;
48:
49: while (it.hasNext()) {
50: start = ((Integer) it.next()).intValue();
51:
52: int possibleEnd = findNext(mailboxSource, start + 5, '\n') + 1;
53:
54: mboxHeaderMatcher.reset(mailboxSource.subSequence(start,
55: possibleEnd - 1));
56: while (!mboxHeaderMatcher.find() && it.hasNext()) {
57: start = ((Integer) it.next()).intValue();
58: possibleEnd = findNext(mailboxSource, start + 5, '\n') + 1;
59: mboxHeaderMatcher.reset(mailboxSource.subSequence(
60: start, possibleEnd));
61: }
62:
63: messages.add(new MboxMessage(new Integer(newUid++),
64: lastEnd, start - lastEnd));
65:
66: lastEnd = possibleEnd;
67: }
68:
69: messages.add(new MboxMessage(new Integer(newUid++), lastEnd,
70: mailboxSource.length() - lastEnd));
71:
72: return (MboxMessage[]) messages.toArray(new MboxMessage[0]);
73: }
74:
75: private static int findNext(Source source, int pos, char ch) {
76: pos++;
77: while (!source.isEOF()) {
78: if (source.charAt(pos) == ch) {
79: return pos;
80: } else {
81: pos++;
82: }
83: }
84:
85: return -1;
86: }
87:
88: }
|