1 17 18 package org.apache.james.util.dbcp; 19 20 import java.io.PrintWriter ; 21 import java.io.StringWriter ; 22 23 import java.sql.Connection ; 24 import java.sql.SQLException ; 25 26 import java.util.Vector ; 27 28 import javax.naming.Context ; 29 import javax.naming.NamingException ; 30 import javax.naming.InitialContext ; 31 32 34 import org.apache.commons.dbcp.BasicDataSource; 35 42 43 import org.apache.avalon.excalibur.datasource.DataSourceComponent; 44 import org.apache.avalon.framework.activity.Disposable; 45 import org.apache.avalon.framework.configuration.Configurable; 46 import org.apache.avalon.framework.configuration.Configuration; 47 import org.apache.avalon.framework.configuration.ConfigurationException; 48 import org.apache.avalon.framework.logger.AbstractLogEnabled; 49 50 88 public class JdbcDataSource extends AbstractLogEnabled 89 implements Configurable, 90 Disposable, 91 DataSourceComponent { 92 93 BasicDataSource source = null; 94 97 100 public void configure(final Configuration configuration) 101 throws ConfigurationException { 102 try { 104 String driver = configuration.getChild("driver").getValue(null); 105 Class.forName(driver); 106 107 String dburl = configuration.getChild("dburl").getValue(null); 108 String user = configuration.getChild("user").getValue(null); 109 String password = configuration.getChild("password").getValue(null); 110 111 source = new BasicDataSource() { 115 protected synchronized javax.sql.DataSource createDataSource() 116 throws SQLException { 117 if (dataSource != null) { 118 return (dataSource); 119 } else { 120 javax.sql.DataSource ds = super.createDataSource(); 121 connectionPool.setTestOnBorrow(true); 122 connectionPool.setTestOnReturn(true); 123 return ds; 124 } 125 } 126 }; 127 128 source.setDriverClassName(driver); 129 source.setUrl(dburl); 130 source.setUsername(user); 131 source.setPassword(password); 132 source.setMaxActive(configuration.getChild("max").getValueAsInteger(2)); 133 source.setMaxIdle(configuration.getChild("max_idle").getValueAsInteger(0)); 134 source.setValidationQuery(configuration.getChild("keep-alive").getValue(null)); 135 138 source.setMaxWait(configuration.getChild("max_wait").getValueAsInteger(5000)); 140 141 final java.io.Writer writer = new java.io.CharArrayWriter () { 146 public void flush() { 147 if (JdbcDataSource.this.getLogger().isErrorEnabled()) { 149 JdbcDataSource.this.getLogger().error(toString()); 150 } 151 reset(); } 153 }; 154 155 source.setLogWriter(new PrintWriter (writer, true)); 156 157 168 169 179 180 193 194 195 source.getConnection().close(); 197 } catch (Exception e) { 198 throw new ConfigurationException("Error configurable datasource", e); 199 } 200 } 201 202 205 public void dispose() { 206 try { 208 source.close(); 209 } catch (SQLException sqle) { 210 sqle.printStackTrace(); 211 } 212 } 213 214 217 public Connection getConnection() throws SQLException { 218 return source.getConnection(); 219 } 220 } 221 | Popular Tags |