import java.sql.*;
import java.io.*;
import java.util.*;
import java.util.Date;
import javax.naming.InitialContext;
import javax.sql.*;
public class DBConnectionManager {
private PrintWriter log;
private InitialContext context;
private DataSource myDS;
/**
* A private constructor since this is a Singleton
*/
public DBConnectionManager() {
init();
}
/**
* Returns a connection to the named pool.
*
* @param name The pool name as defined in the properties file
* @param con The Connection
*/
public synchronized void freeDBConnection(String name, DBConnection dbcon) {
try {
dbcon.close();
}
catch (Exception e) {
log(e, e.toString());
}
}
/**
* Returns an open connection. If no one is available, and the max
* number of connections has not been reached, a new connection is
* created.
*
* @param name The pool name as defined in the properties file
* @return Connection The connection or null
*/
public synchronized DBConnection getDBConnection(String name) {
try {
return new DBConnection(myDS.getConnection());
}
catch (Exception e) {
log(e, e.toString());
}
return null;
}
/**
* Loads properties and initializes the instance with its values.
*/
private void init() {
InputStream is = getClass().getResourceAsStream("/db.properties");
Properties dbProps = new Properties();
try {
dbProps.load(is);
}
catch (Exception e) {
System.err.println("Can't read the properties file. " +
"Make sure db.properties is in the CLASSPATH");
return;
}
String logFile = dbProps.getProperty("logfile", "DBConnectionManager.log");
try {
log = new PrintWriter(new FileWriter(logFile, true), true);
}
catch (IOException e) {
System.err.println("Can't open the log file: " + logFile);
log = new PrintWriter(System.err);
}
String datasource = dbProps.getProperty("datasource", "jdbc/OracleCoreDS_ejms");
try {
context = new InitialContext();
myDS = (DataSource) context.lookup(datasource);
}
catch (Exception e) {
log(e, e.toString());
}
}
/**
* Writes a message to the log file.
*/
private void log(String msg) {
log.println(new Date() + ": " + msg);
}
/**
* Writes a message with an Exception to the log file.
*/
private void log(Throwable e, String msg) {
log.println(new Date() + ": " + msg);
e.printStackTrace(log);
}
}
db.properties