SqliteTable: fixups to schema handling
[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 SqliteDB {
11
12     public Graylist(String filename) throws SQLException {
13         super(filename);
14         SqliteTable whitelist = getTable("whitelist", "(ip unique)");
15         SqliteTable graylist  = getTable("graylist",  "(ip,fromaddr,toaddr,date,PRIMARY KEY(ip,fromaddr,toaddr))");
16         graylist.reap("date");
17     }
18
19     public synchronized void addWhitelist(InetAddress ip) {
20         try {
21             PreparedStatement add    = conn.prepareStatement("insert or replace into 'whitelist' values(?)");
22             add.setString(1, ip.getHostAddress());
23             add.executeUpdate();
24         } catch (SQLException e) { throw new RuntimeException(e); }
25     }
26
27     public synchronized boolean isWhitelisted(InetAddress ip) {
28         try {
29             PreparedStatement check = conn.prepareStatement("select * from 'whitelist' where ip=?");
30             check.setString(1, ip.getHostAddress());
31             ResultSet rs = check.executeQuery();
32             return !rs.isAfterLast();
33         } catch (SQLException e) { throw new RuntimeException(e); }
34     }
35
36     public synchronized long getGrayListTimestamp(InetAddress ip, String from, String to) {
37         try {
38             PreparedStatement check =
39                 conn.prepareStatement("select date from graylist where ip=? and fromaddr=? and toaddr=?");
40             check.setString(1, ip.getHostAddress());
41             check.setString(2, from);
42             check.setString(3, to);
43             ResultSet rs = check.executeQuery();
44             if (rs.isAfterLast()) return 0;
45             return rs.getTimestamp(1).getTime();
46         } catch (SQLException e) { throw new RuntimeException(e); }
47     }
48
49     public synchronized void setGrayListTimestamp(InetAddress ip, String from, String to, long date) {
50         try {
51             PreparedStatement check =
52                 conn.prepareStatement("insert or replace into graylist (ip,fromaddr,toaddr,date) values(?,?,?,?)");
53             check.setString(1, ip.getHostAddress());
54             check.setString(2, from);
55             check.setString(3, to);
56             check.setTimestamp(4, new Timestamp(date));
57             check.executeUpdate();
58         } catch (SQLException e) { throw new RuntimeException(e); }
59     }
60
61 }
62