/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package vn.mobileid.jackrabbit.uat.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.concurrent.locks.ReentrantLock; import org.apache.log4j.Logger; /** * * @author cuongdvh */ public class DatabaseConnection { final static Logger logger = Logger.getLogger(DatabaseConnection.class); private static DatabaseConnection instance = null; private static ReentrantLock lock = new ReentrantLock(); private static String URL_CFG; private static String USERNAME_CFG; private static String PASSWORD_CFG; //public static AtomicInteger cntConnections = new AtomicInteger(0); //public static AtomicInteger openConFail = new AtomicInteger(0); //public static int max = 0; public static void setURL_CFG(String uRL_CFG) { URL_CFG = uRL_CFG; } public static void setUSERNAME_CFG(String uSERNAME_CFG) { USERNAME_CFG = uSERNAME_CFG; } public static void setPASSWORD_CFG(String pASSWORD_CFG) { PASSWORD_CFG = pASSWORD_CFG; } private String url; private String userName; private String password; public DatabaseConnection(String url, String userName, String password) throws InstantiationException, IllegalAccessException, ClassNotFoundException{ this.url = url + "?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false"; this.userName = userName; this.password = password; Class.forName("com.mysql.cj.jdbc.Driver").newInstance(); } public static DatabaseConnection getInstance() { if(instance != null) return instance; lock.lock(); if(instance != null){ lock.unlock(); return instance; } try { instance = new DatabaseConnection(URL_CFG, USERNAME_CFG, PASSWORD_CFG); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } lock.unlock(); return instance; } public Connection createConnection() throws SQLException { /*int counter = cntConnections.incrementAndGet(); logger.info("Create connection " + counter); lock.lock(); if(max < counter){ max = counter; logger.info("*************Max DB connections: " + max); } lock.unlock();*/ try{ return DriverManager.getConnection(url, userName, password); } catch (SQLException e) { // TODO: handle exception e.printStackTrace(); //openConFail.incrementAndGet(); throw e; } } public int releaseConnection(Connection conn) throws SQLException{ if(conn != null) conn.close(); return 0; /*int cons = cntConnections.decrementAndGet(); logger.info("Release connection " + cons); return cons;*/ } }