factor reap() out of SqliteTable constructor
[org.ibex.mail.git] / src / org / ibex / mail / Graylist.java
1 package org.ibex.mail;
2 // todo: periodically flush out old graylist entries
3
4 import java.sql.*;
5 import java.net.*;
6 import java.io.*;
7 import java.util.*;
8 import java.sql.Timestamp;
9
10 public class Graylist extends SqliteTable {
11
12     public Graylist(String filename) {
13         super(filename,
14               new String[] {
15                   "create table if not exists 'whitelist' (ip unique)",
16                   "create table if not exists 'graylist' (ip,fromaddr,toaddr,date, primary key(ip,fromaddr,toaddr))"
17               });
18         reap("graylist", "date");
19     }
20
21     public synchronized void addWhitelist(InetAddress ip) {
22         try {
23             PreparedStatement add    = conn.prepareStatement("insert or replace into 'whitelist' values(?)");
24             add.setString(1, ip.getHostAddress());
25             add.executeUpdate();
26         } catch (SQLException e) { throw new RuntimeException(e); }
27     }
28
29     public synchronized boolean isWhitelisted(InetAddress ip) {
30         try {
31             PreparedStatement check = conn.prepareStatement("select * from 'whitelist' where ip=?");
32             check.setString(1, ip.getHostAddress());
33             ResultSet rs = check.executeQuery();
34             return !rs.isAfterLast();
35         } catch (SQLException e) { throw new RuntimeException(e); }
36     }
37
38     public synchronized long getGrayListTimestamp(InetAddress ip, String from, String to) {
39         try {
40             PreparedStatement check =
41                 conn.prepareStatement("select date from graylist where ip=? and fromaddr=? and toaddr=?");
42             check.setString(1, ip.getHostAddress());
43             check.setString(2, from);
44             check.setString(3, to);
45             ResultSet rs = check.executeQuery();
46             if (rs.isAfterLast()) return 0;
47             return rs.getTimestamp(1).getTime();
48         } catch (SQLException e) { throw new RuntimeException(e); }
49     }
50
51     public synchronized void setGrayListTimestamp(InetAddress ip, String from, String to, long date) {
52         try {
53             PreparedStatement check =
54                 conn.prepareStatement("insert or replace into graylist (ip,fromaddr,toaddr,date) values(?,?,?,?)");
55             check.setString(1, ip.getHostAddress());
56             check.setString(2, from);
57             check.setString(3, to);
58             check.setTimestamp(4, new Timestamp(date));
59             check.executeUpdate();
60         } catch (SQLException e) { throw new RuntimeException(e); }
61     }
62
63 }
64