Advertisement
Guest User

Untitled

a guest
Jul 3rd, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.04 KB | None | 0 0
  1.   /*
  2.      * Database connector Craig Framework v4
  3.      * Database Connection management - Craig Framework v4
  4.       */
  5.  
  6.         public class DatabaseConnection {
  7.             private static final Logger log = LoggerFactory.getErrLogger();
  8.             private static final HashMap<Integer, ConWrapper> connections =
  9.                             new HashMap();
  10.         private static String dbDriver, dbUrl, dbUser, dbPass;
  11.             private static boolean propsInited = false;
  12.             private static long connectionTimeOut = 5 * 60 * 1000; // 5 minutes
  13.      
  14.         private DatabaseConnection() {}
  15.      
  16.         public static Connection getConnection() {
  17.                     Thread cThread = Thread.currentThread();
  18.                     int threadID = (int) cThread.getId();
  19.                     ConWrapper ret = connections.get(threadID);
  20.      
  21.                     if (ret == null) {
  22.                             Connection retCon = connectToDB();
  23.                             ret = new ConWrapper(retCon);
  24.                             ret.id = threadID;
  25.                             connections.put(threadID, ret);
  26.                             log.info("[Database] Thread [" + threadID + "] has created a new Database Connection.");
  27.                     }
  28.      
  29.                     return ret.getConnection();
  30.         }
  31.      
  32.             private static long getWaitTimeout(Connection con) {
  33.                     Statement stmt = null;
  34.                     ResultSet rs = null;
  35.                     try {
  36.                             stmt = con.createStatement();
  37.                             rs = stmt.executeQuery("SHOW VARIABLES 'wait_timeout'");
  38.                             if (rs.next()) {
  39.                                     return Math.max(1000, rs.getInt(2) * 1000 - 1000);
  40.                             } else {
  41.                                     return -1;
  42.                             }
  43.                     } catch (SQLException ex) {
  44.                             return -1;
  45.                     } finally {
  46.                             if (stmt != null) {
  47.                                     try {
  48.                                             stmt.close();
  49.                                     } catch (SQLException ex) {
  50.                                     } finally {
  51.                                             if (rs != null) {
  52.                                                     try {
  53.                                                             rs.close();
  54.                                                     } catch (SQLException ex1) {}
  55.                                             }
  56.                                     }
  57.                             }
  58.                     }
  59.             }
  60.      
  61.             private static Connection connectToDB() {
  62.                     if (!propsInited) {
  63.                             PropertyReader dbReader;
  64.      
  65.                             try {
  66.                                     dbReader = PropertyReader.load("db.cfg");
  67.                             } catch (IOException ex) {
  68.                                     throw new DatabaseException(ex);
  69.                             }
  70.      
  71.                             dbDriver = dbReader.getProperty("driver");
  72.                             dbUrl = dbReader.getProperty("url");
  73.                             dbUser = dbReader.getProperty("user");
  74.                             dbPass = dbReader.getProperty("password");
  75.                             try {
  76.                                     connectionTimeOut = Long.parseLong(dbReader.getProperty("timeout"));
  77.                             } catch (Exception e) {
  78.                                     log.warn("[Database] Cannot read Connection Timeout Information, using default: " + connectionTimeOut);
  79.                             }
  80.                     }
  81.      
  82.                     try {
  83.                             Class.forName(dbDriver);    // touch the MySQL driver
  84.                     } catch (ClassNotFoundException e) {
  85.                             throw new DatabaseException(e);
  86.                     }
  87.      
  88.                     try {
  89.                             Connection con = DriverManager.getConnection(dbUrl, dbUser, dbPass);
  90.                             if (!propsInited) {
  91.                                     long timeout = getWaitTimeout(con);
  92.                                     if (timeout == -1) {
  93.                                             log.error("[Database] Failed to read Wait_Timeout, using " + connectionTimeOut + " instead.");
  94.                                     } else {
  95.                                             connectionTimeOut = timeout;
  96.                                             log.info("[Database] Timeout is " + connectionTimeOut + " milliseconds.");
  97.                                     }
  98.                                     propsInited = true;
  99.                             }
  100.                             return con;
  101.                     } catch (SQLException e) {
  102.                             throw new DatabaseException(e);
  103.                     }
  104.             }
  105.      
  106.             static class ConWrapper {
  107.                     private long lastAccessTime = 0;
  108.                     private Connection connection;
  109.                     private int id;
  110.      
  111.                     public ConWrapper(Connection con) {
  112.                             this.connection = con;
  113.                     }
  114.      
  115.                     public Connection getConnection() {
  116.                             if (expiredConnection()) {
  117.                                     log.info("[Database] Connection #" + id + " has gone stale. Reconnecting..");
  118.                                     try { // Assume that the connection is stale
  119.                                             connection.close();
  120.                                     } catch (Throwable err) {
  121.                                             // Who cares
  122.                                     }
  123.                                     this.connection = connectToDB();
  124.                             }
  125.      
  126.                             lastAccessTime = System.currentTimeMillis(); // Record Access
  127.                             return this.connection;
  128.                     }
  129.      
  130.                     /**
  131.                      * Returns whether this connection has expired
  132.                      * @return
  133.                      */
  134.                     public boolean expiredConnection() {
  135.                             if (lastAccessTime == 0) {
  136.                                     return false;
  137.                             }
  138.                             try {
  139.                                     return System.currentTimeMillis() - lastAccessTime >= connectionTimeOut || connection.isClosed();
  140.                             } catch (Throwable ex) {
  141.                                     return true;
  142.                             }
  143.                     }
  144.             }
  145.      
  146.         public static void closeAll() throws SQLException {
  147.             for (ConWrapper con : connections.values()) {
  148.                 con.connection.close();
  149.             }
  150.                     connections.clear();
  151.         }
  152.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement