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 Headers headers() { return new Headers(new Stream(new ByteArrayInputStream(header)), true); }
110 public Message message(Cache cache) { try {
111 FileInputStream fis = null;
113 return Message.newMessage(new Fountain.File(new File(cache.dir.getParent() + slash + name)));
114 } finally { if (fis != null) fis.close(); }
115 } catch (IOException e) { throw new MailException.IOException(e);
116 } catch (Message.Malformed e) { throw new MailException(e.getMessage()); }
119 // Transactions //////////////////////////////////////////////////////////////////////////////
121 public static Transaction create(File f) throws IOException {
122 final boolean seen = f.lastModified() == MAGIC_DATE;
123 final String name = f.getName();
124 final byte[] header = new Headers(new Stream(new FileInputStream(f)), true).getString().getBytes();
125 return new Transaction() {
126 public void executeOn(Object o, Date now) {
127 Cache cache = (Cache)o;
128 synchronized(cache) {
129 Entry e = new Entry(name, seen, cache.uidNext++, header);
131 cache.byuid.put(e.uid, e);
132 cache.byname.put(e.name, e);
136 public Transaction seen(File f, final boolean seen) {
137 f.setLastModified(seen ? MAGIC_DATE : System.currentTimeMillis());
138 final int uid = this.uid;
139 return new Transaction() {
140 public void executeOn(Object o, Date now) {
141 Cache cache = (Cache)o;
142 synchronized(cache) {
143 cache.get(uid).seen = seen;
146 public Transaction delete(File f) {
147 if (f != null && f.exists()) f.delete();
148 final int uid = this.uid;
149 return new Transaction() {
150 public void executeOn(Object o, Date now) {
151 Cache cache = (Cache)o;
152 synchronized(cache) {
153 Cache.Entry e = cache.get(uid);
154 cache.byname.remove(e.name);
155 cache.linear.remove(e);
156 cache.byuid.remove(uid);
162 // Helpers //////////////////////////////////////////////////////////////////////////////
164 private static void rmDashRf(File f) throws IOException {
165 if (!f.isDirectory()) { f.delete(); return; }
166 String[] children = f.list();
167 for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
171 private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
176 lock = new RandomAccessFile(this.path.getAbsolutePath() + slash + ".lock", "rw").getChannel().tryLock();
177 if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
179 File cacheDir = new File(path.getAbsolutePath() + slash + ".cache");
181 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
182 cache = (Cache)prevayler.prevalentSystem();
183 } catch (Throwable t) {
184 Log.warn(this, "error while attempting to reconstitute a FileBasedMailbox.cache:");
186 Log.warn(this, "discarding cache...");
188 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
189 cache = (Cache)prevayler.prevalentSystem();
191 cache.init(prevayler);
195 public Mailbox.Iterator iterator() { return new Iterator(); }
196 public int uidValidity() { return cache.uidValidity; }
197 public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
198 public String[] children() {
200 String[] list = path.list();
201 for(int i=0; i<list.length; i++) {
202 File f = new File(path.getAbsolutePath() + slash + list[i]);
203 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
205 return (String[])vec.copyInto(new String[vec.size()]);
208 public int uidNext() { return cache.uidNext(); }
209 public synchronized void add(Message message, int flags) {
211 String name, fullname; File target, f;
212 for(int i = cache.uidNext(); ; i++) {
214 fullname = path.getAbsolutePath() + slash + name;
215 target = new File(fullname);
216 f = new File(target.getCanonicalPath() + "-");
217 if (!f.exists() && !target.exists()) break;
218 Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
220 Stream stream = new Stream(new FileOutputStream(f));
221 message.getStream().transcribe(stream);
223 f.renameTo(new File(fullname));
224 f = new File(fullname);
225 if ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) f.setLastModified(MAGIC_DATE);
226 prevayler.execute(Cache.Entry.create(f));
227 } catch (IOException e) { throw new MailException.IOException(e); }
228 Log.info(this, path + " <= " + message.summary());
231 private class Iterator extends Mailbox.Default.Iterator {
233 private Cache.Entry entry() { return cache.getLinear(cur); }
234 private File file() { return new File(cache.dir.getParent() + slash + entry().name); }
235 public Headers head() { return done() ? null : entry().headers(); }
236 public boolean done() { return cur >= cache.size(); }
237 public boolean next() { cur++; return !done(); }
238 public boolean seen() { return done() ? false : entry().seen(); }
239 public boolean recent() { return false; }
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); }