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 = Math.abs(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 long time = System.currentTimeMillis();
59 Log.info(this, "initializing maildir " + dir.getParent());
61 // Drop entries whose files have vanished
62 ArrayList<Transaction> kill = new ArrayList<Transaction>();
63 for(String s : byname.keySet())
64 if (!new File(dir.getParent() + slash + s).exists())
65 kill.add(byname.get(s).delete(null));
66 for(Transaction t : kill) prevayler.execute(t);
68 // Make entries for new files which have appeared
69 for(String file : new File(dir.getParent()).list()) {
70 File f = new File(dir.getParent() + slash + file);
71 if (file.charAt(0)!='.' && !f.isDirectory()) {
74 prevayler.execute(Entry.create(f));
75 else if ((f.lastModified() == MAGIC_DATE) != e.seen())
76 prevayler.execute(e.seen(f, !e.seen()));
80 // Take a snapshot for posterity
81 if (System.currentTimeMillis() - time > 1000 * 5)
82 Log.info(this, " done initializing maildir " + dir.getParent());
83 new Thread() { public void run() {
84 try { prevayler.takeSnapshot(); } catch (Exception e) { Log.error(this, e); } } }.start();
88 public synchronized int size() { return linear.size(); }
89 public synchronized int uidNext() { return uidNext; }
90 public synchronized Entry get(int uid) { return byuid.get(uid); }
91 public synchronized Entry getLinear(int num) { return linear.get(num); }
92 public synchronized Entry get(String name) { return byname.get(name); }
94 public static class Entry implements Serializable {
95 private final byte[] header;
96 public final String name;
99 private Entry(String name, boolean seen, int uid, byte[] header) {
100 this.name = name; this.seen = seen; this.uid = uid; this.header = header; }
102 // Accessors //////////////////////////////////////////////////////////////////////////////
104 public boolean seen() { return seen; }
105 public MIME.Headers headers() { return new MIME.Headers(new Stream(new ByteArrayInputStream(header)), true); }
106 public Message message(Cache cache) { try {
107 FileInputStream fis = null;
109 fis = new FileInputStream(cache.dir.getParent() + slash + name);
110 return Message.newMessage(new Stream(fis));
111 } finally { if (fis != null) fis.close(); }
112 } catch (IOException e) { throw new MailException.IOException(e);
113 } catch (Message.Malformed e) { throw new MailException(e.getMessage()); }
116 // Transactions //////////////////////////////////////////////////////////////////////////////
118 public static Transaction create(File f) throws IOException {
119 final boolean seen = f.lastModified() == MAGIC_DATE;
120 final String name = f.getName();
121 final byte[] header = new MIME.Headers(new Stream(new FileInputStream(f)), true).toString().getBytes();
122 return new Transaction() {
123 public void executeOn(Object o, Date now) {
124 Cache cache = (Cache)o;
125 synchronized(cache) {
126 Entry e = new Entry(name, seen, cache.uidNext++, header);
128 cache.byuid.put(e.uid, e);
129 cache.byname.put(e.name, e);
133 public Transaction seen(File f, final boolean seen) {
134 f.setLastModified(seen ? MAGIC_DATE : System.currentTimeMillis());
135 final int uid = this.uid;
136 return new Transaction() {
137 public void executeOn(Object o, Date now) {
138 Cache cache = (Cache)o;
139 synchronized(cache) {
140 cache.get(uid).seen = seen;
143 public Transaction delete(File f) {
144 if (f != null && f.exists()) f.delete();
145 final int uid = this.uid;
146 return new Transaction() {
147 public void executeOn(Object o, Date now) {
148 Cache cache = (Cache)o;
149 synchronized(cache) {
150 Cache.Entry e = cache.get(uid);
151 cache.byname.remove(e.name);
152 cache.linear.remove(e);
153 cache.byuid.remove(uid);
159 // Helpers //////////////////////////////////////////////////////////////////////////////
161 private static void rmDashRf(File f) throws IOException {
162 if (!f.isDirectory()) { f.delete(); return; }
163 String[] children = f.list();
164 for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
168 private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
173 lock = new RandomAccessFile(this.path.getAbsolutePath() + slash + ".lock", "rw").getChannel().tryLock();
174 if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
176 File cacheDir = new File(path.getAbsolutePath() + slash + ".cache");
178 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
179 cache = (Cache)prevayler.prevalentSystem();
180 } catch (Throwable t) {
181 Log.warn(this, "error while attempting to reconstitute a FileBasedMailbox.cache:");
183 Log.warn(this, "discarding cache...");
185 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
186 cache = (Cache)prevayler.prevalentSystem();
188 cache.init(prevayler);
192 public Mailbox.Iterator iterator() { return new Iterator(); }
193 public int uidValidity() { return cache.uidValidity; }
194 public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
195 public String[] children() {
197 String[] list = path.list();
198 for(int i=0; i<list.length; i++) {
199 File f = new File(path.getAbsolutePath() + slash + list[i]);
200 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
202 return (String[])vec.copyInto(new String[vec.size()]);
205 public int uidNext() { return cache.uidNext(); }
206 public synchronized void add(Message message, int flags) {
208 String name, fullname; File target, f;
209 for(int i = cache.uidNext(); ; i++) {
211 fullname = path.getAbsolutePath() + slash + name;
212 target = new File(fullname);
213 f = new File(target.getCanonicalPath() + "-");
214 if (!f.exists() && !target.exists()) break;
215 Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
217 FileOutputStream fo = new FileOutputStream(f);
218 Stream stream = new Stream(fo);
219 if (message.envelope != null) {
220 stream.println("X-org.ibex.mail.headers.envelope.From: " + message.envelope.from);
221 stream.println("X-org.ibex.mail.headers.envelope.To: " + message.envelope.to);
223 message.dump(stream);
225 f.renameTo(new File(fullname));
226 f = new File(fullname);
227 if ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) f.setLastModified(MAGIC_DATE);
228 prevayler.execute(Cache.Entry.create(f));
229 } catch (IOException e) { throw new MailException.IOException(e); }
230 Log.info(this, path + " <= " + message.summary());
233 private class Iterator extends Mailbox.Default.Iterator {
235 private Cache.Entry entry() { return cache.getLinear(cur); }
236 private File file() { return new File(cache.dir.getParent() + slash + entry().name); }
237 public MIME.Headers head() { return done() ? null : entry().headers(); }
238 public boolean done() { return cur >= cache.size(); }
239 public boolean next() { cur++; return !done(); }
240 public boolean seen() { return done() ? false : entry().seen(); }
241 public int num() { return cur+1; } // EUDORA insists that message numbers start at 1, not 0
242 public int uid() { return done() ? -1 : entry().uid; }
243 public void delete() { prevayler.execute(entry().delete(file())); }
244 public void seen(boolean seen) { prevayler.execute(entry().seen(file(), seen)); }
245 public Message cur() { return entry().message(cache); }