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 transient final Hashtable<Integer,Entry> byuid = new Hashtable<Integer,Entry>();
48 public final File dir;
49 private int uidNext = 0;
51 public Cache(File dir) { this.dir = dir; }
53 public void init(Prevayler prevayler) throws IOException {
55 Log.info(this, "initializing maildir " + dir.getAbsolutePath());
56 boolean invalid = false;
57 for(String s : byname.keySet()) create(prevayler, s);
58 for(String file : new File(dir.getParent()).list())
59 if (file.charAt(0)!='.' && !(new File(dir.getAbsolutePath() + slash + file).isDirectory()))
60 create(prevayler, file);
61 Log.info(this, " done initializing maildir " + dir.getAbsolutePath());
62 prevayler.takeSnapshot();
65 public synchronized void create(Prevayler prevayler, String name) throws IOException {
66 if (get(name) != null) return;
67 new Entry(this, prevayler, name);
70 public synchronized int size() { return byname.size(); }
71 public synchronized int uidNext(boolean increment) { return increment ? uidNext++ : uidNext; }
72 public synchronized Entry get(int uid) { return byuid.get(uid); }
73 public synchronized Entry get(String name) { return byname.get(name); }
75 public static class Entry implements Serializable {
76 public final MIME.Headers headers;
77 public final String name;
81 public Entry(Cache cache, Prevayler prevayler, String name) throws IOException {
82 seen = name.endsWith(".s");
83 this.name = seen ? name.substring(0, name.length() - 2) : name;
84 headers = new MIME.Headers(new Stream(new FileInputStream(cache.dir.getAbsolutePath()+slash+name)), true);
85 prevayler.execute(new Transaction() {
86 public void executeOn(Object o, Date now) {
87 Cache cache = (Cache)o;
89 Entry.this.uid = cache.uidNext(true);
90 cache.byuid.put(Entry.this.uid, Entry.this);
91 cache.byname.put(Entry.this.name, Entry.this);
95 public int uid() { return uid; }
96 public boolean seen() { return seen; }
97 public void seen(Cache cache, boolean seen) {
98 String base = cache.dir.getAbsolutePath() + slash + name;
99 File target = new File(base + (seen?".s":""));
100 if (target.exists()) return;
101 new File(base + (seen?"":".s")).renameTo(target);
103 public void delete(Cache cache) {
104 String base = cache.dir.getAbsolutePath() + slash + name;
105 File target = new File(base);
106 if (!target.exists()) target = new File(base + ".s");
107 if (target.exists()) target.delete();
109 public Message message(Cache cache) { try {
110 String base = cache.dir.getAbsolutePath() + slash + name;
111 File target = new File(base);
112 if (!target.exists()) target = new File(base + ".s");
113 FileInputStream fis = null;
115 fis = new FileInputStream(target);
116 return new Message(new Stream(fis), new Message.Envelope(null, null, new Date(target.lastModified())));
117 } finally { if (fis != null) fis.close(); }
118 } catch (IOException e) { throw new MailException.IOException(e);
119 } catch (Message.Malformed e) { throw new MailException(e.getMessage()); }
124 private static void rmDashRf(File f) throws IOException {
125 if (!f.isDirectory()) { f.delete(); return; }
126 String[] children = f.list();
127 for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
131 private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
136 lock = new RandomAccessFile(this.path.getAbsolutePath() + slash + ".lock", "rw").getChannel().tryLock();
137 if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
139 File cacheDir = new File(path.getAbsolutePath() + slash + ".cache");
141 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
142 cache = (Cache)prevayler.prevalentSystem();
143 } catch (Throwable t) {
144 Log.warn(this, "error while attempting to reconstitute a FileBasedMailbox.cache:");
146 Log.warn(this, "discarding cache...");
148 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
149 cache = (Cache)prevayler.prevalentSystem();
151 cache.init(prevayler);
155 public Mailbox.Iterator iterator() { return new Iterator(); }
156 public int uidValidity() { return cache.uidValidity; }
157 public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
158 public String[] children() {
160 String[] list = path.list();
161 for(int i=0; i<list.length; i++) {
162 File f = new File(path.getAbsolutePath() + slash + list[i]);
163 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
165 return (String[])vec.copyInto(new String[vec.size()]);
168 public int uidNext() { return cache.uidNext(false); }
169 public synchronized void add(Message message, int flags) {
170 Log.info(path, message.summary());
172 final String name = path.getAbsolutePath() + slash + cache.uidNext(true) + "." +
173 ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN ? "s" : "");
174 File target = new File(name);
175 File f = new File(target.getCanonicalPath() + "-");
176 if (f.exists() || target.exists())
177 throw new RuntimeException("aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
178 FileOutputStream fo = new FileOutputStream(f);
179 Stream stream = new Stream(fo);
180 if (message.envelope != null) {
181 stream.println("X-org.ibex.mail.headers.envelope.From: " + message.envelope.from);
182 stream.println("X-org.ibex.mail.headers.envelope.To: " + message.envelope.to);
184 message.dump(stream);
186 f.renameTo(new File(name));
187 new Cache.Entry(cache, prevayler, name);
188 } catch (IOException e) { throw new MailException.IOException(e); }
191 private class Iterator extends Mailbox.Default.Iterator implements Serializable {
193 private Cache.Entry entry() { return cache.get(cur); }
194 public MIME.Headers head() { return done() ? null : entry().headers; }
195 public boolean done() { return cur >= cache.size(); }
196 public boolean next() { cur++; return !done(); }
197 public boolean seen() { return done() ? false : entry().seen(); }
198 public int num() { return cur+1; } // EUDORA insists that message numbers start at 1, not 0
199 public int uid() { return done() ? -1 : entry().uid(); }
200 public Message cur() { return done() ? null : entry().message(cache); }
201 public void seen(final boolean seen) {
203 final int cur = this.cur;
204 prevayler.execute(new Transaction() {
205 public void executeOn(Object c, Date d) {
206 ((Cache)c).get(cur).seen((Cache)c, seen); } });
208 public void delete() {
210 final int cur = this.cur;
211 prevayler.execute(new Transaction() {
212 public void executeOn(Object c, Date d) {
213 ((Cache)c).get(cur).delete((Cache)c); } });