1 package org.ibex.mail.target;
2 import org.prevayler.*;
3 import org.ibex.mail.*;
4 import org.ibex.util.*;
8 import java.nio.channels.*;
13 /** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
14 public class FileBasedMailbox extends Mailbox.Default {
16 public static final long MAGIC_DATE = 0;
18 private static final char slash = File.separatorChar;
19 private static final WeakHashMap<String,FileBasedMailbox> instances = new WeakHashMap<String,FileBasedMailbox>();
20 public String toString() { return "[FileBasedMailbox " + path.getAbsolutePath() + "]"; }
21 public Mailbox slash(String name, boolean create) { return getFileBasedMailbox(path.getAbsolutePath()+slash+name, create); }
23 // FIXME: should be a File()
24 public static synchronized FileBasedMailbox getFileBasedMailbox(String path, boolean create) {
26 FileBasedMailbox ret = instances.get(path);
28 if (!create && !(new File(path).exists())) return null;
29 instances.put(path, ret = new FileBasedMailbox(new File(path)));
32 } catch (Exception e) {
33 Log.error(FileBasedMailbox.class, e);
39 // Instance //////////////////////////////////////////////////////////////////////////////
42 private FileLock lock;
43 private Prevayler prevayler;
46 public static class Cache implements Serializable {
47 public final int uidValidity = new Random().nextInt();
48 private final Hashtable<String,Entry> byname = new Hashtable<String,Entry>();
49 private final Hashtable<Integer,Entry> byuid = new Hashtable<Integer,Entry>();
50 private final ArrayList<Entry> linear = new ArrayList<Entry>();
51 public final File dir;
52 private int uidNext = 0;
54 public Cache(File dir) { this.dir = dir; }
56 public void init(final Prevayler prevayler) throws IOException {
58 Log.info(this, "initializing maildir " + dir.getParent());
60 // Drop entries whose files have vanished
61 ArrayList<Transaction> kill = new ArrayList<Transaction>();
62 for(String s : byname.keySet())
63 if (!new File(dir.getParent() + slash + s).exists())
64 kill.add(byname.get(s).delete(null));
65 for(Transaction t : kill) prevayler.execute(t);
67 // Make entries for new files which have appeared
68 for(String file : new File(dir.getParent()).list()) {
69 File f = new File(dir.getParent() + slash + file);
70 if (file.charAt(0)!='.' && !(f.isDirectory())) {
73 prevayler.execute(Entry.create(f));
74 else if ((f.lastModified() == MAGIC_DATE) != e.seen())
75 prevayler.execute(e.seen(f, !e.seen()));
79 // Take a snapshot for posterity
80 Log.info(this, " done initializing maildir " + dir.getParent());
81 new Thread() { public void run() {
82 try { prevayler.takeSnapshot(); } catch (Exception e) { Log.error(this, e); } } }.start();
86 public synchronized int size() { return linear.size(); }
87 public synchronized int uidNext() { return uidNext; }
88 public synchronized Entry get(int uid) { return byuid.get(uid); }
89 public synchronized Entry getLinear(int num) { return linear.get(num); }
90 public synchronized Entry get(String name) { return byname.get(name); }
92 public static class Entry implements Serializable {
93 private final byte[] header;
94 public final String name;
97 private Entry(String name, boolean seen, int uid, byte[] header) {
98 this.name = name; this.seen = seen; this.uid = uid; this.header = header; }
100 // Accessors //////////////////////////////////////////////////////////////////////////////
102 public boolean seen() { return seen; }
103 public MIME.Headers headers() { return new MIME.Headers(new Stream(new ByteArrayInputStream(header)), true); }
104 public Message message(Cache cache) { try {
105 FileInputStream fis = null;
107 fis = new FileInputStream(cache.dir.getParent() + slash + name);
108 return new Message(new Stream(fis), new Message.Envelope(null, null, null));
109 } finally { if (fis != null) fis.close(); }
110 } catch (IOException e) { throw new MailException.IOException(e);
111 } catch (Message.Malformed e) { throw new MailException(e.getMessage()); }
114 // Transactions //////////////////////////////////////////////////////////////////////////////
116 public static Transaction create(File f) throws IOException {
117 final boolean seen = f.lastModified() == MAGIC_DATE;
118 final String name = f.getName();
119 final byte[] header = new MIME.Headers(new Stream(new FileInputStream(f)), true).toString().getBytes();
120 return new Transaction() {
121 public void executeOn(Object o, Date now) {
122 Cache cache = (Cache)o;
123 synchronized(cache) {
124 Entry e = new Entry(name, seen, cache.uidNext++, header);
126 cache.byuid.put(e.uid, e);
127 cache.byname.put(e.name, e);
131 public Transaction seen(File f, final boolean seen) {
132 f.setLastModified(seen ? MAGIC_DATE : System.currentTimeMillis());
133 final int uid = this.uid;
134 return new Transaction() {
135 public void executeOn(Object o, Date now) {
136 Cache cache = (Cache)o;
137 synchronized(cache) {
138 cache.get(uid).seen = seen;
141 public Transaction delete(File f) {
142 if (f != null && f.exists()) f.delete();
143 final int uid = this.uid;
144 return new Transaction() {
145 public void executeOn(Object o, Date now) {
146 Cache cache = (Cache)o;
147 synchronized(cache) {
148 Cache.Entry e = cache.get(uid);
149 cache.byname.remove(e.name);
150 cache.linear.remove(e);
151 cache.byuid.remove(uid);
157 // Helpers //////////////////////////////////////////////////////////////////////////////
159 private static void rmDashRf(File f) throws IOException {
160 if (!f.isDirectory()) { f.delete(); return; }
161 String[] children = f.list();
162 for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
166 private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
171 lock = new RandomAccessFile(this.path.getAbsolutePath() + slash + ".lock", "rw").getChannel().tryLock();
172 if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
174 File cacheDir = new File(path.getAbsolutePath() + slash + ".cache");
176 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
177 cache = (Cache)prevayler.prevalentSystem();
178 } catch (Throwable t) {
179 Log.warn(this, "error while attempting to reconstitute a FileBasedMailbox.cache:");
181 Log.warn(this, "discarding cache...");
183 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
184 cache = (Cache)prevayler.prevalentSystem();
186 cache.init(prevayler);
190 public Mailbox.Iterator iterator() { return new Iterator(); }
191 public int uidValidity() { return cache.uidValidity; }
192 public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
193 public String[] children() {
195 String[] list = path.list();
196 for(int i=0; i<list.length; i++) {
197 File f = new File(path.getAbsolutePath() + slash + list[i]);
198 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
200 return (String[])vec.copyInto(new String[vec.size()]);
203 public int uidNext() { return cache.uidNext(); }
204 public synchronized void add(Message message, int flags) {
205 Log.info(path, message.summary());
207 String name, fullname; File target, f;
208 for(int i = cache.uidNext(); ; i++) {
210 fullname = path.getAbsolutePath() + slash + name;
211 target = new File(fullname);
212 f = new File(target.getCanonicalPath() + "-");
213 if (!f.exists() && !target.exists()) break;
214 Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
216 FileOutputStream fo = new FileOutputStream(f);
217 Stream stream = new Stream(fo);
218 if (message.envelope != null) {
219 stream.println("X-org.ibex.mail.headers.envelope.From: " + message.envelope.from);
220 stream.println("X-org.ibex.mail.headers.envelope.To: " + message.envelope.to);
222 message.dump(stream);
224 f.renameTo(new File(fullname));
225 f = new File(fullname);
226 if ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) f.setLastModified(MAGIC_DATE);
227 prevayler.execute(Cache.Entry.create(f));
228 } catch (IOException e) { throw new MailException.IOException(e); }
231 private class Iterator extends Mailbox.Default.Iterator {
233 private Cache.Entry entry() { return cache.getLinear(cur); }
234 private File file() { return new File(cache.dir.getParent() + slash + entry().name); }
235 public MIME.Headers head() { return done() ? null : entry().headers(); }
236 public boolean done() { return cur >= cache.size(); }
237 public boolean next() { cur++; return !done(); }
238 public boolean seen() { return done() ? false : entry().seen(); }
239 public int num() { return cur+1; } // EUDORA insists that message numbers start at 1, not 0
240 public int uid() { return done() ? -1 : entry().uid; }
241 public void delete() { prevayler.execute(entry().delete(file())); }
242 public void seen(boolean seen) { prevayler.execute(entry().seen(file(), seen)); }
243 public Message cur() { return entry().message(cache); }