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, PreparedStatement> statements = new HashMap<String, PreparedStatement>();
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 PreparedStatement prepare(String query) throws SQLException {
49 PreparedStatement statement = statements.get(query);
50 if (statement == null) {
51 statement = c.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
52 statements.put(query, statement);
57 private long lastAction = System.currentTimeMillis();
59 private void ensureOpen() {
60 if (System.currentTimeMillis() - lastAction > CONNECTION_TIMEOUT * 1000L) {
62 ResultSet rs = adHoc.executeQuery("SELECT 1");
64 lastAction = System.currentTimeMillis();
66 } catch (SQLException e) {
71 lastAction = System.currentTimeMillis();
74 public static int lastInsertId(PreparedStatement query) throws SQLException {
75 ResultSet rs = query.getGeneratedKeys();
77 int id = rs.getInt(1);
82 private static ThreadLocal<DatabaseConnection> instances = new ThreadLocal<DatabaseConnection>() {
85 protected DatabaseConnection initialValue() {
86 return new DatabaseConnection();
90 public static DatabaseConnection getInstance() {
91 return instances.get();
94 public static boolean isInited() {
95 return credentials != null;
98 public static void init(Properties conf) {
99 if (credentials != null) {
100 throw new Error("Re-initiaizing is forbidden.");
105 public void beginTransaction() throws SQLException {
106 c.setAutoCommit(false);
109 public void commitTransaction() throws SQLException {
111 c.setAutoCommit(true);
114 public void quitTransaction() {
116 if ( !c.getAutoCommit()) {
118 c.setAutoCommit(true);
120 } catch (SQLException e) {