2 // todo: periodically flush out old graylist entries
8 import java.sql.Timestamp;
10 public class Graylist {
12 private Connection conn;
14 public Graylist(String filename) {
16 Class.forName("org.sqlite.JDBC");
17 conn = DriverManager.getConnection("jdbc:sqlite:"+filename);
18 conn.prepareStatement("create table if not exists "+
19 "'whitelist' (ip unique)").executeUpdate();
20 conn.prepareStatement("create table if not exists "+
21 "'graylist' (ip,fromaddr,toaddr,date, primary key(ip,fromaddr,toaddr))").executeUpdate();
23 catch (SQLException e) { throw new RuntimeException(e); }
24 catch (ClassNotFoundException e) { throw new RuntimeException(e); }
27 public synchronized void addWhitelist(InetAddress ip) {
29 PreparedStatement add = conn.prepareStatement("insert or replace into 'whitelist' values(?)");
30 add.setString(1, ip.getHostAddress());
32 } catch (SQLException e) { throw new RuntimeException(e); }
35 public synchronized boolean isWhitelisted(InetAddress ip) {
37 PreparedStatement check = conn.prepareStatement("select * from 'whitelist' where ip=?");
38 check.setString(1, ip.getHostAddress());
39 ResultSet rs = check.executeQuery();
40 return !rs.isAfterLast();
41 } catch (SQLException e) { throw new RuntimeException(e); }
44 public synchronized long getGrayListTimestamp(InetAddress ip, String from, String to) {
46 PreparedStatement check =
47 conn.prepareStatement("select date from graylist where ip=? and fromaddr=? and toaddr=?");
48 check.setString(1, ip.getHostAddress());
49 check.setString(2, from);
50 check.setString(3, to);
51 ResultSet rs = check.executeQuery();
52 if (rs.isAfterLast()) return 0;
53 return rs.getTimestamp(1).getTime();
54 } catch (SQLException e) { throw new RuntimeException(e); }
57 public synchronized void setGrayListTimestamp(InetAddress ip, String from, String to, long date) {
59 PreparedStatement check =
60 conn.prepareStatement("insert or replace into graylist (ip,fromaddr,toaddr,date) values(?,?,?,?)");
61 check.setString(1, ip.getHostAddress());
62 check.setString(2, from);
63 check.setString(3, to);
64 check.setTimestamp(4, new Timestamp(date));
65 check.executeUpdate();
66 } catch (SQLException e) { throw new RuntimeException(e); }