⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dbconnectionmanager.java

📁 java xml开发指南(初学者推荐)Java Xml 编程指南书籍源码
💻 JAVA
字号:
package MyNa.utils;
import java.util.*;
import java.sql.*;

public class DBConnectionManager extends Cache { //singleton class

static private PropertyGroups pG;
static private Hashtable drivers;

static Logger errLg,adminLg;

static String dbUser=null,dbPwd=null,dbUrl=null; //defaults
static int dbTimeout=100,dbInitSize=2,dbMaxSize=3;

protected DBConnectionManager()throws Exception{
  pG=new PropertyGroups("/DBConnMgr.properties");
  adminLg=new Logger(pG.getProperty("admin.log","DBadmin.log"));
  errLg=new Logger(pG.getProperty("err.log","DBerr.log"));
//adminLg.logIt("dbconnectionmanager properties "+pG);
  dbUrl=pG.getProperty("dbUrl",dbUrl); // alter defaults if needed
  dbUser=pG.getProperty("dbUser",dbUser);
  dbPwd=pG.getProperty("dbPwd",dbPwd);
  dbTimeout=topIntProp("dbTimeout",dbTimeout);
  dbMaxSize=topIntProp("dbMaxSize",dbMaxSize);
  dbInitSize=topIntProp("dbInitSize",dbInitSize);
  initDrivers(pG.getProperties("driver"));
  Enumeration pools=pG.propertyKeys();
  while(pools.hasMoreElements()){
    String name=(String)pools.nextElement();
    if(!"driver".equals(name))
      initPool(name,pG.getProperties(name));
    }
}

public void addDriver(String name)throws Exception{
  if(null==name || name.length()==0 || null!=drivers.get(name))return;
  try{
    Driver driver=(Driver)Class.forName(name).newInstance();
    DriverManager.registerDriver(driver);
    drivers.put(name,driver);
    adminLg.logIt("Registered JDBC driver: "+name);
  }catch(Exception ex){
    errLg.logIt("can't register JDBC driver: "+name);
    throw new Exception("can't register JDBC driver: "+name);
  }
}

protected void initDrivers(Properties drivernames)throws Exception{
  // each has the property "true" or some such...not yet used
  drivers=new Hashtable();
  Enumeration names=drivernames.keys();
  while(names.hasMoreElements())
    addDriver((String)names.nextElement());
}
    
/* sample DBConnMgr.properties file, somewhere on the CLASSPATH;
specifies log files, defaults, drivers, and each preloaded pool

admin.log=/C:/MyNa/DBadmin.log
err.log=/C:/MyNa/DBerr.log
dbUser=
dbPwd=
dbTimeout=100
dbInitSize=3
dbMaxSize=4
driver_sun.jdbc.odbc.JdbcOdbcDriver=true
phones_dbUrl=jdbc:odbc:PHONEBOOK
phones_dbUser=
phones_dbPwd=
phones_dbTimeout=200
phones_dbInitSize=2
phones_dbMaxSize=0
flowers_dbUrl=jdbc:odbc:BIRTHDAYS
flowers_dbUser=JaneSchmoe
flowers_dbPwd=v1ryS2cr3t4v5
flowers_dbTimeout=200
flowers_dbInitSize=1
flowers_dbMaxSize=3

*/

private int topIntProp(String key,int def)throws Exception{
  String S=pG.getProperty(key);
  if(null==S)return def;
  return intKey(key,S);
}

private int intKey(String key,String intStr)throws Exception{
  try{return Integer.parseInt(intStr);}
  catch(Exception ex){
    String msg="DBConnectionManager: integer key "+key+"='"+intStr+"'";
    errLg.logIt(msg);
    throw new Exception(msg);
    }
}
private int getInt(Properties p,String key,int def)throws Exception{
  int R=def; 
  String S=p.getProperty(key,pG.getProperty(key));
  if(null!=S)return intKey(key,S);
  return R;
}

private void initPool(String poolName,Properties props)
     throws Exception{
  String url=props.getProperty("dbUrl",dbUrl);
  if(null==url || url.length()==0){
    String msg="No dbUrl for connection pool "+poolName+" in "+props;
    errLg.logIt(msg);
    throw new Exception(msg);
    }
  String usr=props.getProperty("dbUser",dbUser);
  String pwd=props.getProperty("dbPwd",dbPwd);
  int timeout=getInt(props,"dbTimeout",dbTimeout);
  int maxSize=getInt(props,"dbMaxSize",dbMaxSize);
  int initSize=getInt(props,"dbInitSize",dbInitSize);
  DBConnectionPool cP=
    new DBConnectionPool(url+"--"+usr,url,usr,pwd,timeout,initSize,maxSize,
                          errLg,adminLg);
  put(url,usr,pwd,cP);
  adminLg.logIt("created pool "+poolName+" for "+url+"--"+usr+" "+
                    new java.util.Date());
}

public DBConnectionPool getConnectionPool(String url,
                        String usr,String pwd)throws Exception{
  if(null==url || url.length()==0)url=dbUrl;
  if(null==url || url.length()==0)
    throw new Exception("no dbUrl for connection pool");

/*
 // you may wish to map individual usr/pwds to group versions:

    Authorization auth = pwdMgr.checkPassword(url,usr,pwd);
    url=auth.url; usr=auth.usr; pwd=auth.pwd;   

*/

  DBConnectionPool cP=(DBConnectionPool)get(url,usr,pwd);
  if(null!=cP)adminLg.logIt("retrieved pool for "+url+"--"+usr);
  if(null!=cP)return cP;
  cP=new DBConnectionPool(url+"--"+usr,url,usr,pwd,
                          dbTimeout,dbInitSize,dbMaxSize,
                          errLg,adminLg);
  put(url,usr,pwd,cP);
  adminLg.logIt("created new pool "+url+"--"+usr+" "+new java.util.Date());
  return cP;
}

public boolean freeItem(Object ob){ 
  // called by freeSpace; override if you need to do anything here.
  if(!(ob instanceof DBConnectionPool)){
    errLg.logIt("non-connectionpool in DBConnectionManager cache!"+ob);
    return false;
    }
  DBConnectionPool cP=(DBConnectionPool)ob;
  cP.close();
  return true;
}

protected class Authorization { // simply a package for three items.
  String url,usr,pwd;
  public Authorization(String a,String b,String c){url=a;usr=b;pwd=c;}
}


protected class PasswordManager {
/*
 This class is a suggested means of maximizing connection-sharing,
 using groups with group passwords. It does require that you keep
 a PASSWORDS table of the form
   url,usr,pwd,groupUrl,groupUsr,groupPwd.

*/
  Connection pwdConnection=null; // kept permanently open
  PreparedStatement groupPwd=null;
  final String queryStr="SELECT groupUrl,groupUsr,groupPwd "
              + " FROM PASSWORDS WHERE url=? AND usr=? and pwd=?";
  Authorization auth;
  boolean passAlong; // if true, unrecognized individuals are passed to db

  public PasswordManager(String url,String usr,String pwd,boolean pass)
      throws Exception{
    passAlong=pass;
    auth = new Authorization(url,usr,pwd);
    pwdConnection= DriverManager.getConnection(url,usr,pwd);
    groupPwd=pwdConnection.prepareStatement(queryStr);
 }
  public Authorization checkPassword(String url,String usr,String pwd)
     throws Exception{
      groupPwd.setString(1,url);
      groupPwd.setString(2,usr);
      groupPwd.setString(3,pwd);
      ResultSet rs=groupPwd.executeQuery();
      if(!rs.next()){
         rs.close(); 
         if(passAlong)return new Authorization(url,usr,pwd);
         else return new Authorization(url,"","");
         }
      Authorization auth
        =new Authorization(rs.getString(1),rs.getString(2),rs.getString(3));
      rs.close();
      return auth;
}

}



private static Cache instance=null; // the one and only class instance
private static int clients=0;       // how many are asking us?

protected void init(){super.init();}  // e.g., register, init loggers
 
public static synchronized Cache getInstance(){ 
  try{
    if(null==instance)instance=new DBConnectionManager();
    clients++;
    adminLg.logIt("added new ConnectionManager instance");
    return instance;
  }catch(Exception ex){ex.printStackTrace(); return null;}
}

public static synchronized int freeInstance(){ 
  if(null==instance)return 0;
  clients--;
adminLg.logIt("freed instance of connectionmanager, leaving "+clients);
  if(clients==0)
     try{close(); // all gone, and the cache with it.
     adminLg.logIt("closed connection manager");
     }catch(Exception ex){errLg.logIt("freeInstance ",ex);}
  return clients;
}

public static synchronized boolean close()throws Exception{ 
  clients=0;
  while(0==instance.freeSpace(10000)); // succeeded in freeing that many!
  instance=null;
  Enumeration enum=drivers.keys();
  while(enum.hasMoreElements()){
    String key=(String)enum.nextElement();
    try{
      DriverManager.deregisterDriver((Driver)drivers.get(key));
      adminLg.logIt("Deregistered driver "+key);
    }catch(Exception ex){
      String msg="failed to deregister driver "+key;
      errLg.logIt(msg);
      throw new Exception(msg); // or return false, or just skip it
    }
  }
  return true;

}



}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -