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.*;
16 import javax.servlet.*;
17 import javax.servlet.http.*;
19 /** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
20 public class FileBasedMailbox extends Mailbox.Default {
22 public static final long MAGIC_DATE = 0;
23 private static final char slash = File.separatorChar;
24 private static final WeakHashMap<String,FileBasedMailbox> instances = new WeakHashMap<String,FileBasedMailbox>();
25 public String toString() { return "[FileBasedMailbox " + path.getAbsolutePath() + "]"; }
26 public Mailbox slash(String name, boolean create) { return getFileBasedMailbox(path.getAbsolutePath()+slash+name, create); }
28 // FIXME: should be a File()
29 public static synchronized FileBasedMailbox getFileBasedMailbox(String path, boolean create) {
31 FileBasedMailbox ret = instances.get(path);
33 if (!create && !(new File(path).exists())) return null;
34 instances.put(path, ret = new FileBasedMailbox(new File(path)));
37 } catch (Exception e) {
38 Log.error(FileBasedMailbox.class, e);
43 // Instance //////////////////////////////////////////////////////////////////////////////
46 private FileLock lock;
48 private int uidValidity;
50 // Helpers //////////////////////////////////////////////////////////////////////////////
52 private static void rmDashRf(File f) throws IOException {
53 if (!f.isDirectory()) { f.delete(); return; }
54 String[] children = f.list();
55 for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
59 private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
64 File lockfile = new File(this.path.getAbsolutePath() + slash + ".lock");
65 lock = new RandomAccessFile(lockfile, "rw").getChannel().tryLock();
66 if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
67 uidValidity = (int)(lockfile.lastModified() & 0xffffffff);
69 String[] files = path.list();
70 for(int i=0; i<files.length; i++) {
72 if (files[i].indexOf('.') != -1) files[i] = files[i].substring(0, files[i].indexOf('.'));
73 int n = Integer.parseInt(files[i]);
74 if (n>=uidNext) uidNext = n;
75 } catch(Exception e) { /* DELIBERATE */ }
80 public Mailbox.Iterator iterator() { return new Iterator(); }
81 public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
82 public String[] children() {
84 String[] list = path.list();
85 for(int i=0; i<list.length; i++) {
86 File f = new File(path.getAbsolutePath() + slash + list[i]);
87 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
89 return (String[])vec.copyInto(new String[vec.size()]);
92 public int uidValidity() { return uidValidity; }
93 public int uidNext() { return uidNext; }
94 public synchronized void add(Message message, int flags) {
96 String name, fullname; File target, f;
97 for(int i = uidNext; ; i++) {
99 fullname = path.getAbsolutePath() + slash + name;
100 target = new File(fullname);
101 f = new File(target.getCanonicalPath() + "-");
102 if (!f.exists() && !target.exists()) break;
103 Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
105 Stream stream = new Stream(new FileOutputStream(f));
106 message.getStream().transcribe(stream);
108 f.renameTo(new File(fullname));
110 f = new File(fullname);
111 if ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) f.setLastModified(MAGIC_DATE);
112 } catch (IOException e) { throw new MailException.IOException(e); }
113 Log.info(this, path + " <= " + message.summary());
116 private class Iterator extends Mailbox.Default.Iterator {
118 String[] files = path.list(new FilenameFilter() { public boolean accept(File dir, String name) {
119 return name.endsWith(".");
121 private File file() { return new File(path.getAbsolutePath() + slash + files[cur]); }
122 public boolean done() { return cur >= files.length; }
123 public boolean next() { cur++; return !done(); }
124 public boolean seen() { return false; }
125 public boolean recent() { return false; }
126 public int num() { return cur+1; } // EUDORA insists that message numbers start at 1, not 0
127 public int uid() { return done() ? -1 : Integer.parseInt(files[cur].substring(0, files[cur].length()-1)); }
128 public void delete() { File f = file(); if (f != null && f.exists()) f.delete(); }
129 public void seen(boolean seen) { }
130 public Headers head() {
131 if (done()) return null;
132 FileInputStream fis = null;
134 return new Headers(new Stream(new FileInputStream(file())));
135 } catch (IOException e) { throw new MailException.IOException(e);
136 } finally { if (fis != null) try { fis.close(); } catch (Exception e) { /* DELIBERATE */ } }
138 public Message cur() {
139 FileInputStream fis = null;
141 return Message.newMessage(new Fountain.File(file()));
142 //} catch (IOException e) { throw new MailException.IOException(e);
143 } catch (Message.Malformed e) { throw new MailException(e.getMessage());
144 } finally { if (fis != null) try { fis.close(); } catch (Exception e) { /* DELIBERATE */ } }
148 public static class Servlet extends HttpServlet {
149 public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {doGet(request, response);}
150 private void frames(HttpServletRequest request, HttpServletResponse response, boolean top) throws IOException {
151 String basename = request.getServletPath();
152 PrintWriter pw = new PrintWriter(response.getWriter());
153 pw.println("<html>");
155 pw.println(" <frameset rows='30%,*'>");
156 pw.println(" <frame src='"+basename+"?frame=top' marginwidth=0 marginheight=0 name=top/>");
157 pw.println(" <frame src='"+basename+"?frame=bottom' marginwidth=0 marginheight=0 name='bottom'/>");
159 pw.println(" <frameset cols='150,*'>");
160 pw.println(" <frame src='"+basename+"?frame=topleft' marginwidth=0 marginheight=0 name=topleft/>");
161 pw.println(" <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
163 pw.println(" </frameset>");
164 pw.println("</html>");
168 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
169 String frame = request.getParameter("frame");
170 String basename = request.getServletPath();
172 if (frame == null) { frames(request, response, true); return; }
173 if (frame.equals("top")) { frames(request, response, false); return; }
174 if (frame.equals("topleft")) { return; }
176 if (request.getServletPath().indexOf("..") != -1) throw new IOException(".. not allowed in image paths");
177 ServletContext cx = getServletContext();
178 String path = cx.getRealPath(request.getServletPath());
179 Mailbox mbox = FileBasedMailbox.getFileBasedMailbox(path, false);
180 if (mbox == null) throw new IOException("no such mailbox: " + path);
182 Vec msgs = new Vec();
183 for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
184 String[] s = new String[4];
185 Message m = it.cur();
186 s[0] = (m.from==null?"":m.from.toString(true));
188 s[2] = (m.date + "").trim().replaceAll(" "," ");
189 s[3] = it.num() + "";
193 msgs.copyInto(messages = new String[msgs.size()][]);
195 if ("bottom".equals(frame)) { bottom(request, response, messages, mbox); return; }
196 if ("topright".equals(frame)) { topright(request, response, messages); return; }
199 private void bottom(HttpServletRequest request, HttpServletResponse response, String[][] messages, Mailbox mbox)
201 PrintWriter pw = new PrintWriter(response.getWriter());
202 pw.println("<html>");
203 pw.println(" <body>");
204 pw.println(" <pre>");
205 if (request.getParameter("msgnum") != null) {
206 int target = Integer.parseInt(request.getParameter("msgnum"));
207 for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
208 if (it.num() == target) {
209 StringBuffer tgt = new StringBuffer();
210 it.cur().getBody().getStream().transcribe(tgt);
211 pw.println(tgt.toString());
216 pw.println(" </pre>");
217 pw.println(" </body>");
218 pw.println("</html>");
221 private void topright(HttpServletRequest request, HttpServletResponse response, String[][] messages) throws IOException {
222 PrintWriter pw = new PrintWriter(response.getWriter());
223 String basename = request.getServletPath();
224 pw.println("<html>");
225 pw.println(" <head>");
226 pw.println(" <style>");
227 pw.println(" a:link { color: #000; text-decoration: none; }");
228 pw.println(" a:active { color: #f00; text-decoration: none; }");
229 pw.println(" a:visited { color: #777; text-decoration: none; }");
230 pw.println(" a:hover { color: #000; text-decoration: none; }");
231 pw.println(" /* a:hover { color: #00f; text-decoration: none; border-bottom: 1px dotted; } */");
232 pw.println(" </style>");
233 pw.println(" </head>");
234 pw.println(" <body onKeyPress='doKey(event.keyCode)'>");
235 pw.println(" <script>");
236 pw.println(" var chosen = null;");
237 pw.println(" var all = [];");
238 pw.println(" function doKey(x) {");
239 pw.println(" if (chosen == null) { choose(all[0]); return; }");
240 pw.println(" switch(x) {");
241 pw.println(" case 112: if (chosen.id > 0) choose(all[chosen.id-1]); break;");
242 pw.println(" case 110: if (chosen.id < (all.length-1)) choose(all[1+(1*chosen.id)]); break;");
245 pw.println(" function choose(who) {");
246 pw.println(" who.style.background = '#ffc';");
247 pw.println(" if (chosen != null) chosen.style.background = '#aaa';");
248 pw.println(" top.bottom.location='"+basename+"?frame=bottom&msgnum='+who.id;");
249 pw.println(" chosen = who;");
251 pw.println(" </script>");
252 pw.println(" <table width=100% border=0 cellpadding=0 cellspacing=0>");
254 for(int i=0; i<messages.length; i++) {
256 pw.println(" <tr style='background: "+(odd?"#e8eef7":"white")+"' id='"+i+"' "+
257 "onmouseover='this.style.color=\"blue\"' "+
258 "onmouseout='this.style.color=\"black\"' "+
259 "onclick='choose(this);'>");
260 String[] m = messages[i];
261 pw.println("<td style='padding:5px; padding-bottom:2px'>"+m[0]+"</td>");
262 pw.println("<td style='padding:5px; padding-bottom:2px'>"+m[1]+"</td>");
263 pw.println("<td style='padding:5px; padding-bottom:2px'>"+m[2]+"</td>");
265 pw.println("<script> all["+i+"] = document.getElementById('"+i+"'); </script>");
266 pw.println("<tr height=1 bgcolor=black><td colspan=3>");
267 pw.println(" <img src=http://www.xwt.org/images/clearpixel.gif></td></tr>");
269 pw.println(" </table>");
270 pw.println(" </body>");
271 pw.println("</html>");