default implementation of recent()
[org.ibex.mail.git] / src / org / ibex / mail / target / FileBasedMailbox.java
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.
4
5 package org.ibex.mail.target;
6 import org.prevayler.*;
7 import org.ibex.mail.*;
8 import org.ibex.util.*;
9 import org.ibex.io.*;
10 import java.io.*;
11 import java.nio.*;
12 import java.nio.channels.*;
13 import java.net.*;
14 import java.util.*;
15 import java.text.*;
16
17 /** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
18 public class FileBasedMailbox extends Mailbox.Default {
19
20     public static final long MAGIC_DATE = 0;
21
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); }
26
27     // FIXME: should be a File()
28     public static synchronized FileBasedMailbox getFileBasedMailbox(String path, boolean create) {
29         try {
30             FileBasedMailbox ret = instances.get(path);
31             if (ret == null) {
32                 if (!create && !(new File(path).exists())) return null;
33                 instances.put(path, ret = new FileBasedMailbox(new File(path)));
34             }
35             return ret;
36         } catch (Exception e) {
37             Log.error(FileBasedMailbox.class, e);
38             return null;
39         }
40     }
41
42
43     // Instance //////////////////////////////////////////////////////////////////////////////
44
45     private File path;
46     private FileLock lock;
47     private Prevayler prevayler;
48     private Cache cache;
49
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;
57
58         public Cache(File dir) { this.dir = dir; }
59
60         public void init(final Prevayler prevayler) throws IOException {
61             dir.mkdirs();
62             long time = System.currentTimeMillis();
63             Log.info(this, "initializing maildir " + dir.getParent());
64
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);
71
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()) {
76                     Entry e = get(file);
77                     if (e == null)
78                         prevayler.execute(Entry.create(f));
79                     else if ((f.lastModified() == MAGIC_DATE) != e.seen())
80                         prevayler.execute(e.seen(f, !e.seen()));
81                 }
82             }
83
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();
89         }
90
91        
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); }
97
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; }
105
106             // Accessors //////////////////////////////////////////////////////////////////////////////
107
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;
112                 try {
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()); }
118             }
119
120             // Transactions //////////////////////////////////////////////////////////////////////////////
121
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);
131                                 cache.linear.add(e);
132                                 cache.byuid.put(e.uid, e);
133                                 cache.byname.put(e.name, e);
134                             } } };
135             }
136
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;
145                             } } };
146             }
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);
158                             } } };
159             }
160         }
161     }
162
163     // Helpers //////////////////////////////////////////////////////////////////////////////
164
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]));
169         f.delete();
170     }
171
172     private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
173         this.path = path;
174         path.mkdirs();
175
176         // acquire lock
177         lock = new RandomAccessFile(this.path.getAbsolutePath() + slash + ".lock", "rw").getChannel().tryLock();
178         if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
179
180         File cacheDir = new File(path.getAbsolutePath() + slash + ".cache");
181         try {
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:");
186             Log.warn(this, t);
187             Log.warn(this, "discarding cache...");
188             rmDashRf(cacheDir);
189             prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
190             cache = (Cache)prevayler.prevalentSystem();
191         }
192         cache.init(prevayler);
193     }
194
195
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() {
200         Vec vec = new Vec();
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]);
205         }
206         return (String[])vec.copyInto(new String[vec.size()]);
207     }
208
209     public int uidNext() { return cache.uidNext(); }
210     public synchronized void add(Message message, int flags) {
211         try {
212             String name, fullname; File target, f;
213             for(int i = cache.uidNext(); ; i++) {
214                 name = 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());
220             }
221             FileOutputStream fo = new FileOutputStream(f);
222             Stream stream = new Stream(fo);
223             message.dump(stream);
224             fo.close();
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());
231     }
232
233     private class Iterator extends Mailbox.Default.Iterator {
234         int cur = -1;
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 boolean recent() { return false; }
242         public int num() { return cur+1; }  // EUDORA insists that message numbers start at 1, not 0
243         public int uid() { return done() ? -1 : entry().uid; }
244         public void delete() { prevayler.execute(entry().delete(file())); }
245         public void seen(boolean seen) { prevayler.execute(entry().seen(file(), seen)); }
246         public Message cur() { return entry().message(cache); }
247     }
248
249 }