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) { Log.error(this, e); }
79 public String[] sort(String[] s) {
84 public String[] files() {
85 String[] s = path.list(filter);
86 Arrays.sort(s, comparator);
90 private static Comparator<String> comparator = new Comparator<String>() {
91 public int compare(String a, String b) {
92 if (a.indexOf('.')==-1) return a.compareTo(b);
93 if (b.indexOf('.')==-1) return a.compareTo(a);
94 int ai = Integer.parseInt(a.substring(0, a.indexOf('.')));
95 int bi = Integer.parseInt(b.substring(0, b.indexOf('.')));
96 return ai<bi ? -1 : ai>bi ? 1 : 0;
100 public Mailbox.Iterator iterator() { return new Iterator(); }
101 public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
102 public String[] children() {
104 String[] list = sort(path.list());
105 for(int i=0; i<list.length; i++) {
106 File f = new File(path.getAbsolutePath() + slash + list[i]);
107 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
109 return (String[])vec.copyInto(new String[vec.size()]);
112 public int uidValidity() { return uidValidity; }
113 public int uidNext() { return uidNext; }
114 public synchronized void add(Message message, int flags) {
116 String name, fullname; File target, f;
117 for(int i = uidNext; ; i++) {
119 fullname = path.getAbsolutePath() + slash + name;
120 target = new File(fullname);
121 f = new File(target.getCanonicalPath() + "-");
122 if (!f.exists() && !target.exists()) break;
123 Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
125 Stream stream = new Stream(new FileOutputStream(f));
126 message.getStream().transcribe(stream);
128 f.renameTo(new File(fullname));
130 f = new File(fullname);
131 if ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) f.setLastModified(MAGIC_DATE);
132 } catch (IOException e) { throw new MailException.IOException(e); }
133 Log.info(this, path + " <= " + message.summary());
136 private static FilenameFilter filter =
137 new FilenameFilter() { public boolean accept(File dir, String name) {
138 return name.endsWith(".");
141 private class Iterator extends Mailbox.Default.Iterator {
143 String[] files = files();
144 private File file() { return new File(path.getAbsolutePath() + slash + files[cur]); }
145 public boolean done() { return cur >= files.length; }
146 public boolean next() { cur++; return !done(); }
147 public boolean seen() { return false; }
148 public boolean recent() { return false; }
149 public int num() { return cur+1; } // EUDORA insists that message numbers start at 1, not 0
150 public int uid() { return done() ? -1 : Integer.parseInt(files[cur].substring(0, files[cur].length()-1)); }
151 public void delete() { File f = file(); if (f != null && f.exists()) f.delete(); }
152 public void seen(boolean seen) { }
153 public Headers head() {
154 if (done()) return null;
155 FileInputStream fis = null;
157 return new Headers.Original(new Stream(new FileInputStream(file())));
158 } catch (IOException e) { throw new MailException.IOException(e);
159 } finally { if (fis != null) try { fis.close(); } catch (Exception e) { /* DELIBERATE */ } }
161 public Message cur() {
162 FileInputStream fis = null;
164 return Message.newMessage(new Fountain.File(file()));
165 //} catch (IOException e) { throw new MailException.IOException(e);
166 } catch (Message.Malformed e) { throw new MailException(e.getMessage());
167 } finally { if (fis != null) try { fis.close(); } catch (Exception e) { /* DELIBERATE */ } }
171 public static class Servlet extends HttpServlet {
172 public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request, response); }
173 private void frames(HttpServletRequest request, HttpServletResponse response, boolean top) throws IOException {
174 String basename = request.getRequestURI();
175 PrintWriter pw = new PrintWriter(response.getWriter());
176 pw.println("<html>");
178 pw.println(" <frameset rows='30%,*'>");
179 //pw.println(" <frame src='"+basename+"?frame=banner' marginwidth=0 marginheight=0 name=banner/>");
180 //pw.println(" <frame src='"+basename+"?frame=top' marginwidth=0 marginheight=0 name=top/>");
181 pw.println(" <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
182 pw.println(" <frame src='"+basename+"?frame=bottom' marginwidth=0 marginheight=0 name='bottom'/>");
184 pw.println(" <frameset cols='150,*'>");
185 pw.println(" <frame src='"+basename+"?frame=topleft' marginwidth=0 marginheight=0 name=topleft/>");
186 pw.println(" <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
188 pw.println(" </frameset>");
189 pw.println("</html>");
193 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
194 String frame = request.getParameter("frame");
195 String basename = request.getRequestURI();
197 if (frame == null) { frames(request, response, true); return; }
198 if (frame.equals("top")) { frames(request, response, false); return; }
199 if (frame.equals("banner")) { banner(request, response); return; }
200 if (frame.equals("topleft")) { return; }
202 if (request.getServletPath().indexOf("..") != -1) throw new IOException(".. not allowed in image paths");
203 ServletContext cx = getServletContext();
204 String path = cx.getRealPath(request.getServletPath());
205 Mailbox mbox = FileBasedMailbox.getFileBasedMailbox(path, false);
206 if (mbox == null) throw new IOException("no such mailbox: " + path);
208 Vec msgs = new Vec();
209 for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
210 String[] s = new String[4];
211 Message m = it.cur();
212 s[0] = (m.from==null?"":m.from.toString(true));
214 s[2] = (m.date + "").trim().replaceAll(" "," ");
215 s[3] = it.num() + "";
219 msgs.copyInto(messages = new String[msgs.size()][]);
221 if ("bottom".equals(frame)) { bottom(request, response, messages, mbox); return; }
222 if ("topright".equals(frame)) { topright(request, response, messages); return; }
225 private void bottom(HttpServletRequest request, HttpServletResponse response, String[][] messages, Mailbox mbox)
227 PrintWriter pw = new PrintWriter(response.getWriter());
228 pw.println("<html>");
229 pw.println(" <head>");
230 pw.println(" <style>");
231 pw.println(" body { margin: 10px; }");
232 pw.println(" pre {");
233 pw.println(" font-family: monospace;");
234 pw.println(" background-color: #F0F0E0;");
235 pw.println(" color: rgb(0, 0, 0);");
236 pw.println(" padding: 5px;");
237 pw.println(" margin: 0px;");
238 pw.println(" overflow: auto;");
239 //pw.println(" width: 80%;");
240 //pw.println(" border-style: solid;");
241 //pw.println(" border-width: 1px;");
243 pw.println(" </style>");
244 pw.println(" </head>");
245 pw.println(" <body>");
246 if (request.getParameter("msgnum") != null) {
247 int target = Integer.parseInt(request.getParameter("msgnum"));
248 Mailbox.Iterator it = mbox.iterator();
250 if (it.num() == target)
252 if (it.cur() != null) {
253 pw.println(" <table width=100% border=0 cellspacing=0 style='border: 1px black solid; background-color:#F0F0E0;'>");
254 pw.println(" <tr style='border: 1px black solid; font-family: monospace'><td style='padding: 5px'>");
255 Headers h = it.cur().headers;
256 pw.println(" Subject: " + it.cur().subject +"<br>");
257 pw.println(" From: " + it.cur().from +"<br>");
258 pw.println(" Date: " + it.cur().date +"<br>");
260 for(java.util.Enumeration e = h.names(); e.hasMoreElements();) {
261 String key = (String)e.nextElement();
262 if (key==null || key.length()==0 || key.equals("from") ||
263 key.equals("to") || key.equals("subject") || key.equals("date")) continue;
264 key = Character.toUpperCase(key.charAt(0)) + key.substring(1);
265 String val = h.get(key);
266 for(int i=key.length(); i<15; i++)pw.print(" ");
271 pw.print("</td></tr><tr><td style='border-top: 1px black; border-top-style: dotted;'><pre>");
272 StringBuffer tgt = new StringBuffer();
273 it.cur().getBody().getStream().transcribe(tgt);
274 pw.println(tgt.toString());
275 pw.println(" </pre></td></tr></table>");
278 pw.println(" </body>");
279 pw.println("</html>");
284 private void banner(HttpServletRequest request, HttpServletResponse response) throws IOException {
285 String basename = request.getServletPath();
286 String realpath = getServletContext().getRealPath(basename);
287 MailingList list = MailingList.getMailingList(realpath);
288 list.banner(request, response);
291 private void topright(HttpServletRequest request, HttpServletResponse response, String[][] messages) throws IOException {
292 PrintWriter pw = new PrintWriter(response.getWriter());
293 String basename = request.getRequestURI();
294 pw.println("<html>");
295 pw.println(" <head>");
296 pw.println(" <style>");
297 pw.println(" TH, TD, P, LI {");
298 pw.println(" font-family: helvetica, verdana, arial, sans-serif;");
299 pw.println(" font-size: 12px; ");
300 pw.println(" text-decoration:none; ");
302 pw.println(" body { margin: 10px; }");
303 pw.println(" a:link { color: #000; text-decoration: none; }");
304 pw.println(" a:active { color: #f00; text-decoration: none; }");
305 pw.println(" a:visited { color: #777; text-decoration: none; }");
306 pw.println(" a:hover { color: #000; text-decoration: none; }");
307 pw.println(" /* a:hover { color: #00f; text-decoration: none; border-bottom: 1px dotted; } */");
308 pw.println(" </style>");
309 pw.println(" </head>");
310 pw.println(" <body onKeyPress='doKey(event.keyCode)'>");
311 pw.println(" <script>");
312 pw.println(" var chosen = null;");
313 pw.println(" var all = [];");
314 pw.println(" function doKey(x) {");
315 pw.println(" if (chosen == null) { choose(all[0]); return; }");
316 pw.println(" switch(x) {");
317 pw.println(" case 112: if (chosen.id > 0) choose(all[chosen.id-1]); break;");
318 pw.println(" case 110: if (chosen.id < (all.length-1)) choose(all[1+(1*chosen.id)]); break;");
321 pw.println(" function choose(who) {");
322 pw.println(" who.style.background = '#ffc';");
323 pw.println(" if (chosen != null) chosen.style.background = '#ccc';");
324 pw.println(" parent.parent.bottom.location='"+basename+"?frame=bottom&msgnum='+who.id;");
325 pw.println(" chosen = who;");
327 pw.println(" </script>");
328 pw.println(" <div style='border: 1px black solid;'><table width=100% border=0 cellpadding=0 cellspacing=0>");
329 pw.println(" <tr><td style='padding: 4px' bgcolor=#eff7ff>");
331 banner(request, response);
332 pw.println(" </td></tr>");
333 pw.println(" <tr><td>");
334 pw.println(" <table width=100% cellpadding=0 cellspacing=0 style='border-top: 1px black solid; cursor:pointer;'>");
336 for(int i=0; i<messages.length; i++) {
338 String[] m = messages[i];
339 pw.println(" <tr style='cursor:pointer; background: "+(odd?"#e8eef7":"white")+"' id='"+m[3]+"' "+
340 "onmouseover='this.style.color=\"blue\"' "+
341 "onmouseout='this.style.color=\"black\"' "+
342 "onclick='choose(this);'>");
343 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[0]+"</td>");
344 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[1]+"</td>");
345 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[2]+"</td>");
347 pw.println("<script> all["+i+"] = document.getElementById('"+i+"'); </script>");
349 pw.println(" </table>");
350 pw.println(" </td></tr>");
351 pw.println(" </table></div>");
352 pw.println(" </body>");
353 pw.println("</html>");