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 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, new Date()));
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 Log.error(Entry.class, "create with seen = " + seen);
119 final String name = f.getName();
120 final byte[] header = new MIME.Headers(new Stream(new FileInputStream(f)), true).toString().getBytes();
121 return new Transaction() {
122 public void executeOn(Object o, Date now) {
123 Cache cache = (Cache)o;
124 synchronized(cache) {
125 Entry e = new Entry(name, seen, cache.uidNext++, header);
127 cache.byuid.put(e.uid, e);
128 cache.byname.put(e.name, e);
132 public Transaction seen(File f, final boolean seen) {
133 f.setLastModified(seen ? MAGIC_DATE : System.currentTimeMillis());
134 final int uid = this.uid;
135 return new Transaction() {
136 public void executeOn(Object o, Date now) {
137 Cache cache = (Cache)o;
138 synchronized(cache) {
139 cache.get(uid).seen = seen;
142 public Transaction delete(File f) {
143 if (f != null && f.exists()) f.delete();
144 final int uid = this.uid;
145 return new Transaction() {
146 public void executeOn(Object o, Date now) {
147 Cache cache = (Cache)o;
148 synchronized(cache) {
149 Cache.Entry e = cache.get(uid);
150 cache.byname.remove(e.name);
151 cache.linear.remove(e);
152 cache.byuid.remove(uid);
158 // Helpers //////////////////////////////////////////////////////////////////////////////
160 private static void rmDashRf(File f) throws IOException {
161 if (!f.isDirectory()) { f.delete(); return; }
162 String[] children = f.list();
163 for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
167 private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
172 lock = new RandomAccessFile(this.path.getAbsolutePath() + slash + ".lock", "rw").getChannel().tryLock();
173 if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
175 File cacheDir = new File(path.getAbsolutePath() + slash + ".cache");
177 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
178 cache = (Cache)prevayler.prevalentSystem();
179 } catch (Throwable t) {
180 Log.warn(this, "error while attempting to reconstitute a FileBasedMailbox.cache:");
182 Log.warn(this, "discarding cache...");
184 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
185 cache = (Cache)prevayler.prevalentSystem();
187 cache.init(prevayler);
191 public Mailbox.Iterator iterator() { return new Iterator(); }
192 public int uidValidity() { return cache.uidValidity; }
193 public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
194 public String[] children() {
196 String[] list = path.list();
197 for(int i=0; i<list.length; i++) {
198 File f = new File(path.getAbsolutePath() + slash + list[i]);
199 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
201 return (String[])vec.copyInto(new String[vec.size()]);
204 public int uidNext() { return cache.uidNext(); }
205 public synchronized void add(Message message, int flags) {
206 Log.info(path, message.summary());
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); }
232 private class Iterator extends Mailbox.Default.Iterator {
234 private Cache.Entry entry() { return cache.getLinear(cur); }
235 private File file() { return new File(cache.dir.getParent() + slash + entry().name); }
236 public MIME.Headers head() { return done() ? null : entry().headers(); }
237 public boolean done() { return cur >= cache.size(); }
238 public boolean next() { cur++; return !done(); }
239 public boolean seen() { return done() ? false : entry().seen(); }
240 public int num() { return cur+1; } // EUDORA insists that message numbers start at 1, not 0
241 public int uid() { return done() ? -1 : entry().uid; }
242 public void delete() { prevayler.execute(entry().delete(file())); }
243 public void seen(boolean seen) { prevayler.execute(entry().seen(file(), seen)); }
244 public Message cur() { return entry().message(cache); }