d2aec48416903534ff40e6220d4a612eaa54d281
[org.ibex.mail.git] / src / org / ibex / mail / store / MessageStore.java
1 package org.ibex.mail.store;
2 import org.ibex.util.*;
3 import java.io.*;
4 import java.net.*;
5
6 // FIXME: appallingly inefficient
7 public class MessageStore {
8
9     private final String STORAGE_ROOT = System.getProperty("org.ibex.mail.MessageStore.ROOT", "/var/org.ibex.mail/");
10     public final MessageStore root = new MessageStore(STORAGE_ROOT);
11
12     private String path;
13     private MessageStore(String path) throws IOException { new File(this.path = path).mkdirs(); }
14     public MessageStore slash(String name) { return new MessageStore(path + "/" + name); }
15
16     public int[] list() {
17         String[] names = new File(path).list();
18         int[] ret = new int[names.length];
19         for(int i=0, j=0; j<ret.length; i++, j++) {
20             try {
21                 ret[j] = Integer.parseInt(names[i].substring(0, names[i].length - 1));
22             } catch (NumberFormatException nfe) {
23                 Log.warn(MessageStore.class, "NumberFormatException: " + names[i].substring(0, names[i].length - 1));
24                 j--;
25                 int[] newret = new int[ret.length - 1];
26                 System.arrayCopy(ret, 0, newret, 0, newret.length);
27                 ret = newret;
28             }
29         }
30         return ret;
31     }
32
33     /** returns a message identifier */
34     public synchronized int add(StoredMessage message) throws IOException {
35         int[] all = list();
36         int max = 0;
37         for(int i=0; i<all.length; i++) max = Math.max(max, all[i]);
38         int target = max++;
39         File f = new File(path + File.separatorChar + max + ".-");
40         FileOutputStream fo = new FileOutputStream(f);
41         message.dump(fo);
42         fo.close();
43         f.renameTo(path + File.separatorChar + max + ".");
44         return target;
45     }
46
47     public StoredMessage get(int messagenum) throws IOException {
48         File f = new File(path + File.separatorChar + messagenum + ".");        
49         if (!f.exists()) throw new FileNotFoundException(f);
50         return StoredMessage.undump(new FileInputStream(f));
51     }
52
53     // query types: stringmatch (headers, body), header element, deletion status, date range, message size
54     public StoredMessage[] query(int maxResults) {
55         throw new RuntimeException("MessageStore.query() not implemented yet");
56     }
57
58 }