package org.jfox.jdbc.datasource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.Referenceable;
import javax.naming.StringRefAddr;
import javax.sql.DataSource;
import org.huihoo.jfox.system.ComponentSupport;
public class PoolDataSource extends ComponentSupport implements DataSource, Referenceable {
protected ConnectionPool pool = null; private String dbDriver; private String dbURL; private String user; private String password; private int initNum = 2;
private int maxRest = 10;
public PoolDataSource(String dbDriver, String dbURL, String user, String password) throws Exception {
this.dbDriver = dbDriver;
this.dbURL = dbURL;
this.user = user;
this.password = password;
}
public Connection getConnection() throws SQLException {
try {
return pool.getConnection();
}
catch (SQLException sqle) {
throw sqle;
}
catch (Exception e) {
e.printStackTrace();
throw new SQLException(e.getMessage());
}
}
public Connection getConnection(String username, String password)
throws SQLException {
return DriverManager.getConnection(dbURL, username, password);
}
public PrintWriter getLogWriter() throws SQLException {
return DriverManager.getLogWriter();
}
public void setLogWriter(PrintWriter out) throws SQLException {
DriverManager.setLogWriter(out);
}
public void setLoginTimeout(int seconds) throws SQLException {
DriverManager.setLoginTimeout(seconds);
}
public int getLoginTimeout() throws SQLException {
return DriverManager.getLoginTimeout();
}
public Reference getReference() throws NamingException {
Reference ref = new Reference(getClass().getName(), DataSourceObjectFactory.class.getName(), null);
ref.add(new StringRefAddr("dbDriver", dbDriver));
ref.add(new StringRefAddr("dbURL", dbURL));
ref.add(new StringRefAddr("user", user));
ref.add(new StringRefAddr("password", password));
return ref;
}
public String getDbDriver() {
return dbDriver;
}
public String getDbURL() {
return dbURL;
}
public String getUser() {
return user;
}
public String getPassword() {
return password;
}
public int getMaxRest() {
return maxRest;
}
public int getInitNum(){
return initNum;
}
public void setInitNum(int initNum) {
this.initNum = initNum;
}
public void setMaxRest(int maxRest) {
this.maxRest = maxRest;
}
protected void doInit() throws Exception {
pool = new ConnectionPool(dbDriver, dbURL, user, password);
pool.setInitNum(initNum);
pool.setMaxRest(maxRest);
pool.init();
}
protected void doDestroy() throws Exception {
pool.destroy();
}
}