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 String toString() { return "[FileBasedMailbox " + path.getAbsolutePath() + "]"; }
17 private static final char slash = File.separatorChar;
18 private static final WeakHashMap<String,FileBasedMailbox> instances = new WeakHashMap<String,FileBasedMailbox>();
19 public Mailbox slash(String name, boolean create) { return getFileBasedMailbox(path.getAbsolutePath()+slash+name, create); }
21 // FIXME: should be a File()
22 public static synchronized FileBasedMailbox getFileBasedMailbox(String path, boolean create) {
24 FileBasedMailbox ret = instances.get(path);
26 if (!create && !(new File(path).exists())) return null;
27 instances.put(path, ret = new FileBasedMailbox(new File(path)));
30 } catch (Exception e) {
31 Log.error(FileBasedMailbox.class, e);
37 // Instance //////////////////////////////////////////////////////////////////////////////
40 private FileLock lock;
41 private Prevayler prevayler;
44 public static class Cache implements Serializable {
45 public final int uidValidity = new Random().nextInt();
46 private final Hashtable<String,Entry> byname = new Hashtable<String,Entry>();
47 private final Hashtable<Integer,Entry> byuid = new Hashtable<Integer,Entry>();
48 private final ArrayList<Entry> linear = new ArrayList<Entry>();
49 public final File dir;
50 private int uidNext = 0;
52 public Cache(File dir) { this.dir = dir; }
54 public void init(Prevayler prevayler) throws IOException {
56 Log.info(this, "initializing maildir " + dir.getParent());
57 boolean invalid = false;
58 ArrayList<Transaction> kill = new ArrayList<Transaction>();
59 for(String s : byname.keySet()) {
60 String name = dir.getParent() + slash + s;
61 if (!new File(name).exists() && !new File(name+"s").exists()) {
62 Log.error(this, "dropping message " + name);
63 kill.add(new Drop(byname.get(s).uid()));
66 for(Transaction t : kill) prevayler.execute(t);
67 for(String file : new File(dir.getParent()).list())
68 if (file.charAt(0)!='.' && !(new File(dir.getParent() + slash + file).isDirectory()))
69 if (get(file) == null) new Entry(this, prevayler, file);
70 Log.info(this, " done initializing maildir " + dir.getParent());
71 prevayler.takeSnapshot();
74 public static class Drop implements Transaction {
76 public Drop(int uid) { this.uid = uid; }
77 public void executeOn(Object o, Date now) {
80 c.byname.remove(e.name);
86 public synchronized int size() { return linear.size(); }
87 public synchronized int uidNext(boolean increment) { return increment ? uidNext++ : 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) {
91 if (name.endsWith("s")) name = name.substring(0, name.length() - 1);
92 return byname.get(name);
95 public static class Entry implements Serializable {
96 public final MIME.Headers headers;
97 public final String name;
101 public Entry(Cache cache, Prevayler prevayler, String name) throws IOException {
102 seen = name.endsWith("s");
103 this.name = seen ? name.substring(0, name.length() - 1) : name;
104 headers = new MIME.Headers(new Stream(new FileInputStream(cache.dir.getParent()+slash+name)), true);
105 prevayler.execute(new Transaction() {
106 public void executeOn(Object o, Date now) {
107 Cache cache = (Cache)o;
108 synchronized(cache) {
109 Entry.this.uid = cache.uidNext(true);
110 cache.linear.add(Entry.this);
111 cache.byuid.put(Entry.this.uid, Entry.this);
112 cache.byname.put(Entry.this.name, Entry.this);
116 public int uid() { return uid; }
117 public boolean seen() { return seen; }
118 public void seen(Cache cache, boolean seen) {
119 String base = cache.dir.getParent() + slash + name;
120 File target = new File(base + (seen?"s":""));
122 if (target.exists()) return;
123 new File(base + (seen?"":"s")).renameTo(target);
125 public void delete(Cache cache) {
126 String base = cache.dir.getParent() + slash + name;
127 File target = new File(base);
128 if (!target.exists()) target = new File(base + "s");
129 if (target.exists()) target.delete();
131 public Message message(Cache cache) { try {
132 String base = cache.dir.getParent() + slash + name;
133 File target = new File(base);
134 if (!target.exists()) target = new File(base + "s");
135 FileInputStream fis = null;
137 fis = new FileInputStream(target);
138 return new Message(new Stream(fis), new Message.Envelope(null, null, new Date(target.lastModified())));
139 } finally { if (fis != null) fis.close(); }
140 } catch (IOException e) { throw new MailException.IOException(e);
141 } catch (Message.Malformed e) { throw new MailException(e.getMessage()); }
146 private static void rmDashRf(File f) throws IOException {
147 if (!f.isDirectory()) { f.delete(); return; }
148 String[] children = f.list();
149 for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
153 private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
158 lock = new RandomAccessFile(this.path.getAbsolutePath() + slash + ".lock", "rw").getChannel().tryLock();
159 if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
161 File cacheDir = new File(path.getAbsolutePath() + slash + ".cache");
163 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
164 cache = (Cache)prevayler.prevalentSystem();
165 } catch (Throwable t) {
166 Log.warn(this, "error while attempting to reconstitute a FileBasedMailbox.cache:");
168 Log.warn(this, "discarding cache...");
170 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
171 cache = (Cache)prevayler.prevalentSystem();
173 cache.init(prevayler);
177 public Mailbox.Iterator iterator() { return new Iterator(); }
178 public int uidValidity() { return cache.uidValidity; }
179 public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
180 public String[] children() {
182 String[] list = path.list();
183 for(int i=0; i<list.length; i++) {
184 File f = new File(path.getAbsolutePath() + slash + list[i]);
185 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
187 return (String[])vec.copyInto(new String[vec.size()]);
190 public int uidNext() { return cache.uidNext(false); }
191 public synchronized void add(Message message, int flags) {
192 Log.info(path, message.summary());
194 String name; String fullname; File target; File f;
196 name = cache.uidNext(true) + "." + ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN ? "s" : "");
197 fullname = path.getAbsolutePath() + slash + name;
198 target = new File(fullname);
199 f = new File(target.getCanonicalPath() + "-");
200 Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
201 } while (f.exists() || target.exists());
202 FileOutputStream fo = new FileOutputStream(f);
203 Stream stream = new Stream(fo);
204 if (message.envelope != null) {
205 stream.println("X-org.ibex.mail.headers.envelope.From: " + message.envelope.from);
206 stream.println("X-org.ibex.mail.headers.envelope.To: " + message.envelope.to);
208 message.dump(stream);
210 f.renameTo(new File(fullname));
211 new Cache.Entry(cache, prevayler, name);
212 } catch (IOException e) { throw new MailException.IOException(e); }
215 private class Iterator extends Mailbox.Default.Iterator {
217 private Cache.Entry entry() { return cache.getLinear(cur); }
218 public MIME.Headers head() { return done() ? null : entry().headers; }
219 public boolean done() { return cur >= cache.size(); }
220 public boolean next() { cur++; return !done(); }
221 public boolean seen() { return done() ? false : entry().seen(); }
222 public int num() { return cur+1; } // EUDORA insists that message numbers start at 1, not 0
223 public int uid() { return done() ? -1 : entry().uid(); }
224 public Message cur() { return done() ? null : entry().message(cache); }
225 public void seen(boolean seen) { prevayler.execute(new Seen(uid(), seen)); }
226 public void delete() { prevayler.execute(new Delete(uid())); }
229 private static class Delete implements Transaction {
231 public Delete(int uid) { this.uid = uid; }
232 public void executeOn(Object c, Date d) { ((Cache)c).get(uid).delete((Cache)c); }
234 private static class Seen implements Transaction {
236 private boolean seen;
237 public Seen(int uid, boolean seen) { this.uid = uid; this.seen = seen; }
238 public void executeOn(Object c, Date d) { ((Cache)c).get(uid).seen((Cache)c, seen); }