1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
5 package org.ibex.mail.target;
6 import org.prevayler.*;
7 import org.ibex.mail.*;
8 import org.ibex.util.*;
12 import java.nio.channels.*;
17 /** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
18 public class FileBasedMailbox extends Mailbox.Default {
20 public static final long MAGIC_DATE = 0;
22 private static final char slash = File.separatorChar;
23 private static final WeakHashMap<String,FileBasedMailbox> instances = new WeakHashMap<String,FileBasedMailbox>();
24 public String toString() { return "[FileBasedMailbox " + path.getAbsolutePath() + "]"; }
25 public Mailbox slash(String name, boolean create) { return getFileBasedMailbox(path.getAbsolutePath()+slash+name, create); }
27 // FIXME: should be a File()
28 public static synchronized FileBasedMailbox getFileBasedMailbox(String path, boolean create) {
30 FileBasedMailbox ret = instances.get(path);
32 if (!create && !(new File(path).exists())) return null;
33 instances.put(path, ret = new FileBasedMailbox(new File(path)));
36 } catch (Exception e) {
37 Log.error(FileBasedMailbox.class, e);
43 // Instance //////////////////////////////////////////////////////////////////////////////
46 private FileLock lock;
47 private Prevayler prevayler;
50 public static class Cache implements Serializable {
51 public final int uidValidity = Math.abs(new Random().nextInt());
52 private final Hashtable<String,Entry> byname = new Hashtable<String,Entry>();
53 private final Hashtable<Integer,Entry> byuid = new Hashtable<Integer,Entry>();
54 private final ArrayList<Entry> linear = new ArrayList<Entry>();
55 public final File dir;
56 private int uidNext = 0;
58 public Cache(File dir) { this.dir = dir; }
60 public void init(final Prevayler prevayler) throws IOException {
62 long time = System.currentTimeMillis();
63 Log.info(this, "initializing maildir " + dir.getParent());
65 // Drop entries whose files have vanished
66 ArrayList<Transaction> kill = new ArrayList<Transaction>();
67 for(String s : byname.keySet())
68 if (!new File(dir.getParent() + slash + s).exists())
69 kill.add(byname.get(s).delete(null));
70 for(Transaction t : kill) prevayler.execute(t);
72 // Make entries for new files which have appeared
73 for(String file : new File(dir.getParent()).list()) {
74 File f = new File(dir.getParent() + slash + file);
75 if (file.charAt(0)!='.' && !f.isDirectory()) {
78 prevayler.execute(Entry.create(f));
79 else if ((f.lastModified() == MAGIC_DATE) != e.seen())
80 prevayler.execute(e.seen(f, !e.seen()));
84 // Take a snapshot for posterity
85 if (System.currentTimeMillis() - time > 1000 * 5)
86 Log.info(this, " done initializing maildir " + dir.getParent());
87 new Thread() { public void run() {
88 try { prevayler.takeSnapshot(); } catch (Exception e) { Log.error(this, e); } } }.start();
92 public synchronized int size() { return linear.size(); }
93 public synchronized int uidNext() { return uidNext; }
94 public synchronized Entry get(int uid) { return byuid.get(uid); }
95 public synchronized Entry getLinear(int num) { return linear.get(num); }
96 public synchronized Entry get(String name) { return byname.get(name); }
98 public static class Entry implements Serializable {
99 private final byte[] header;
100 public final String name;
101 public final int uid;
102 private boolean seen;
103 private Entry(String name, boolean seen, int uid, byte[] header) {
104 this.name = name; this.seen = seen; this.uid = uid; this.header = header; }
106 // Accessors //////////////////////////////////////////////////////////////////////////////
108 public boolean seen() { return seen; }
109 public MIME.Headers headers() { return new MIME.Headers(new Stream(new ByteArrayInputStream(header)), true); }
110 public Message message(Cache cache) { try {
111 FileInputStream fis = null;
113 fis = new FileInputStream(cache.dir.getParent() + slash + name);
114 return Message.newMessage(new Stream(fis));
115 } finally { if (fis != null) fis.close(); }
116 } catch (IOException e) { throw new MailException.IOException(e);
117 } catch (Message.Malformed e) { throw new MailException(e.getMessage()); }
120 // Transactions //////////////////////////////////////////////////////////////////////////////
122 public static Transaction create(File f) throws IOException {
123 final boolean seen = f.lastModified() == MAGIC_DATE;
124 final String name = f.getName();
125 final byte[] header = new MIME.Headers(new Stream(new FileInputStream(f)), true).toString().getBytes();
126 return new Transaction() {
127 public void executeOn(Object o, Date now) {
128 Cache cache = (Cache)o;
129 synchronized(cache) {
130 Entry e = new Entry(name, seen, cache.uidNext++, header);
132 cache.byuid.put(e.uid, e);
133 cache.byname.put(e.name, e);
137 public Transaction seen(File f, final boolean seen) {
138 f.setLastModified(seen ? MAGIC_DATE : System.currentTimeMillis());
139 final int uid = this.uid;
140 return new Transaction() {
141 public void executeOn(Object o, Date now) {
142 Cache cache = (Cache)o;
143 synchronized(cache) {
144 cache.get(uid).seen = seen;
147 public Transaction delete(File f) {
148 if (f != null && f.exists()) f.delete();
149 final int uid = this.uid;
150 return new Transaction() {
151 public void executeOn(Object o, Date now) {
152 Cache cache = (Cache)o;
153 synchronized(cache) {
154 Cache.Entry e = cache.get(uid);
155 cache.byname.remove(e.name);
156 cache.linear.remove(e);
157 cache.byuid.remove(uid);
163 // Helpers //////////////////////////////////////////////////////////////////////////////
165 private static void rmDashRf(File f) throws IOException {
166 if (!f.isDirectory()) { f.delete(); return; }
167 String[] children = f.list();
168 for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
172 private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
177 lock = new RandomAccessFile(this.path.getAbsolutePath() + slash + ".lock", "rw").getChannel().tryLock();
178 if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
180 File cacheDir = new File(path.getAbsolutePath() + slash + ".cache");
182 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
183 cache = (Cache)prevayler.prevalentSystem();
184 } catch (Throwable t) {
185 Log.warn(this, "error while attempting to reconstitute a FileBasedMailbox.cache:");
187 Log.warn(this, "discarding cache...");
189 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
190 cache = (Cache)prevayler.prevalentSystem();
192 cache.init(prevayler);
196 public Mailbox.Iterator iterator() { return new Iterator(); }
197 public int uidValidity() { return cache.uidValidity; }
198 public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
199 public String[] children() {
201 String[] list = path.list();
202 for(int i=0; i<list.length; i++) {
203 File f = new File(path.getAbsolutePath() + slash + list[i]);
204 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
206 return (String[])vec.copyInto(new String[vec.size()]);
209 public int uidNext() { return cache.uidNext(); }
210 public synchronized void add(Message message, int flags) {
212 String name, fullname; File target, f;
213 for(int i = cache.uidNext(); ; i++) {
215 fullname = path.getAbsolutePath() + slash + name;
216 target = new File(fullname);
217 f = new File(target.getCanonicalPath() + "-");
218 if (!f.exists() && !target.exists()) break;
219 Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
221 FileOutputStream fo = new FileOutputStream(f);
222 Stream stream = new Stream(fo);
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); }