1 package org.cacert.gigi.database;
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.PreparedStatement;
6 import java.sql.ResultSet;
7 import java.sql.SQLException;
8 import java.util.HashMap;
9 import java.util.Properties;
10 import java.sql.Statement;
12 public class DatabaseConnection {
13 public static final int CONNECTION_TIMEOUT = 24 * 60 * 60;
15 HashMap<String, PreparedStatement> statements = new HashMap<String, PreparedStatement>();
16 private static Properties credentials;
18 public DatabaseConnection() {
20 Class.forName(credentials.getProperty("sql.driver"));
21 } catch (ClassNotFoundException e) {
27 private void tryConnect() {
29 c = DriverManager.getConnection(credentials.getProperty("sql.url")
30 + "?zeroDateTimeBehavior=convertToNull",
31 credentials.getProperty("sql.user"),
32 credentials.getProperty("sql.password"));
33 PreparedStatement ps = c
34 .prepareStatement("SET SESSION wait_timeout=?;");
35 ps.setInt(1, CONNECTION_TIMEOUT);
38 adHoc = c.createStatement();
39 } catch (SQLException e) {
43 public PreparedStatement prepare(String query) throws SQLException {
45 PreparedStatement statement = statements.get(query);
46 if (statement == null) {
47 statement = c.prepareStatement(query,
48 Statement.RETURN_GENERATED_KEYS);
49 statements.put(query, statement);
53 long lastAction = System.currentTimeMillis();
54 private void ensureOpen() {
55 if (System.currentTimeMillis() - lastAction > CONNECTION_TIMEOUT * 1000L) {
57 ResultSet rs = adHoc.executeQuery("SELECT 1");
59 lastAction = System.currentTimeMillis();
61 } catch (SQLException e) {
66 lastAction = System.currentTimeMillis();
68 public static int lastInsertId(PreparedStatement query) throws SQLException {
69 ResultSet rs = query.getGeneratedKeys();
71 int id = rs.getInt(1);
75 static ThreadLocal<DatabaseConnection> instances = new ThreadLocal<DatabaseConnection>() {
77 protected DatabaseConnection initialValue() {
78 return new DatabaseConnection();
81 public static DatabaseConnection getInstance() {
82 return instances.get();
84 public static boolean isInited() {
85 return credentials != null;
87 public static void init(Properties conf) {
88 if (credentials != null) {
89 throw new Error("Re-initiaizing is forbidden.");
93 public void beginTransaction() throws SQLException {
94 c.setAutoCommit(false);
96 public void commitTransaction() throws SQLException {
98 c.setAutoCommit(true);
100 public void quitTransaction() {
102 if (!c.getAutoCommit()) {
104 c.setAutoCommit(true);
106 } catch (SQLException e) {