small fixup
[org.ibex.mail.git] / src / org / ibex / mail / target / FileBasedMailbox.java
1 package org.ibex.mail.target;
2 import org.prevayler.*;
3 import org.ibex.mail.*;
4 import org.ibex.util.*;
5 import org.ibex.io.*;
6 import java.io.*;
7 import java.nio.*;
8 import java.nio.channels.*;
9 import java.net.*;
10 import java.util.*;
11 import java.text.*;
12
13 /** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
14 public class FileBasedMailbox extends Mailbox.Default {
15
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); }
20
21     // FIXME: should be a File()
22     public static synchronized FileBasedMailbox getFileBasedMailbox(String path, boolean create) {
23         try {
24             FileBasedMailbox ret = instances.get(path);
25             if (ret == null) {
26                 if (!create && !(new File(path).exists())) return null;
27                 instances.put(path, ret = new FileBasedMailbox(new File(path)));
28             }
29             return ret;
30         } catch (Exception e) {
31             Log.error(FileBasedMailbox.class, e);
32             return null;
33         }
34     }
35
36
37     // Instance //////////////////////////////////////////////////////////////////////////////
38
39     private File path;
40     private FileLock lock;
41     private Prevayler prevayler;
42     private Cache cache;
43
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;
50
51         public Cache(File dir) { this.dir = dir; }
52
53         public void init(Prevayler prevayler) throws IOException {
54             dir.mkdirs();
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();
63         }
64
65         public synchronized void create(Prevayler prevayler, String name) throws IOException {
66             if (get(name) != null) return;
67             new Entry(this, prevayler, name);
68         }
69
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); }
74
75         public static class Entry implements Serializable {
76             public final MIME.Headers headers;
77             public final String name;
78             private int uid;
79             private boolean seen;
80             
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;
88                             synchronized(cache) {
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);
92                             } } });
93             }
94
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);
102             }
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();
108             }
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;
114                 try {
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()); }
120             }
121         }
122     }
123
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]));
128         f.delete();
129     }
130
131     private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
132         this.path = path;
133         path.mkdirs();
134
135         // acquire lock
136         lock = new RandomAccessFile(this.path.getAbsolutePath() + slash + ".lock", "rw").getChannel().tryLock();
137         if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
138
139         File cacheDir = new File(path.getAbsolutePath() + slash + ".cache");
140         try {
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:");
145             Log.warn(this, t);
146             Log.warn(this, "discarding cache...");
147             rmDashRf(cacheDir);
148             prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
149             cache = (Cache)prevayler.prevalentSystem();
150         }
151         cache.init(prevayler);
152     }
153
154
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() {
159         Vec vec = new Vec();
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]);
164         }
165         return (String[])vec.copyInto(new String[vec.size()]);
166     }
167
168     public int uidNext() { return cache.uidNext(false); }
169     public synchronized void add(Message message, int flags) {
170         Log.info(path, message.summary());
171         try {
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);
183             }
184             message.dump(stream);
185             fo.close();
186             f.renameTo(new File(name));
187             new Cache.Entry(cache, prevayler, name);
188         } catch (IOException e) { throw new MailException.IOException(e); }
189     }
190
191     private class Iterator extends Mailbox.Default.Iterator implements Serializable {
192         int cur = -1;
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) {
202             if (done()) return;
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); } });
207         }
208         public void delete() {
209             if (done()) return;
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); } });
214         }
215     }
216 }