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.sql.Statement;
9 import java.util.HashMap;
10 import java.util.Properties;
12 public class DatabaseConnection {
14 public static final int CONNECTION_TIMEOUT = 24 * 60 * 60;
18 private HashMap<String, GigiPreparedStatement> statements = new HashMap<String, GigiPreparedStatement>();
20 private static Properties credentials;
22 private Statement adHoc;
24 public DatabaseConnection() {
26 Class.forName(credentials.getProperty("sql.driver"));
27 } catch (ClassNotFoundException e) {
34 private void tryConnect() {
36 c = DriverManager.getConnection(credentials.getProperty("sql.url") + "?zeroDateTimeBehavior=convertToNull", credentials.getProperty("sql.user"), credentials.getProperty("sql.password"));
37 PreparedStatement ps = c.prepareStatement("SET SESSION wait_timeout=?;");
38 ps.setInt(1, CONNECTION_TIMEOUT);
41 adHoc = c.createStatement();
42 } catch (SQLException e) {
47 public GigiPreparedStatement prepare(String query) {
49 GigiPreparedStatement statement = statements.get(query);
50 if (statement == null) {
52 statement = new GigiPreparedStatement(c.prepareStatement(query, Statement.RETURN_GENERATED_KEYS));
53 } catch (SQLException e) {
56 statements.put(query, statement);
61 private long lastAction = System.currentTimeMillis();
63 private void ensureOpen() {
64 if (System.currentTimeMillis() - lastAction > CONNECTION_TIMEOUT * 1000L) {
66 ResultSet rs = adHoc.executeQuery("SELECT 1");
68 lastAction = System.currentTimeMillis();
70 } catch (SQLException e) {
75 lastAction = System.currentTimeMillis();
78 private static ThreadLocal<DatabaseConnection> instances = new ThreadLocal<DatabaseConnection>() {
81 protected DatabaseConnection initialValue() {
82 return new DatabaseConnection();
86 public static DatabaseConnection getInstance() {
87 return instances.get();
90 public static boolean isInited() {
91 return credentials != null;
94 public static void init(Properties conf) {
95 if (credentials != null) {
96 throw new Error("Re-initiaizing is forbidden.");
101 public void beginTransaction() throws SQLException {
102 c.setAutoCommit(false);
105 public void commitTransaction() throws SQLException {
107 c.setAutoCommit(true);
110 public void quitTransaction() {
112 if ( !c.getAutoCommit()) {
114 c.setAutoCommit(true);
116 } catch (SQLException e) {