1 17 18 21 package org.quartz.utils; 22 23 import java.sql.Connection ; 24 import java.sql.SQLException ; 25 import java.util.Properties ; 26 27 import org.apache.commons.dbcp.BasicDataSource; 28 29 47 public class PoolingConnectionProvider implements ConnectionProvider { 48 49 56 57 58 public static final String DB_DRIVER = "driver"; 59 60 61 public static final String DB_URL = "URL"; 62 63 64 public static final String DB_USER = "user"; 65 66 67 public static final String DB_PASSWORD = "password"; 68 69 70 public static final String DB_MAX_CONNECTIONS = "maxConnections"; 71 72 76 public static final String DB_VALIDATION_QUERY = "validationQuery"; 77 78 79 public static final int DEFAULT_DB_MAX_CONNECTIONS = 10; 80 81 88 89 private BasicDataSource datasource; 90 91 98 99 public PoolingConnectionProvider(String dbDriver, String dbURL, 100 String dbUser, String dbPassword, int maxConnections, 101 String dbValidationQuery) throws SQLException { 102 initialize( 103 dbDriver, dbURL, dbUser, dbPassword, 104 maxConnections, dbValidationQuery); 105 } 106 107 126 public PoolingConnectionProvider(Properties config) throws SQLException { 127 PropertiesParser cfg = new PropertiesParser(config); 128 initialize( 129 cfg.getStringProperty(DB_DRIVER), 130 cfg.getStringProperty(DB_URL), 131 cfg.getStringProperty(DB_USER, ""), 132 cfg.getStringProperty(DB_PASSWORD, ""), 133 cfg.getIntProperty(DB_MAX_CONNECTIONS, DEFAULT_DB_MAX_CONNECTIONS), 134 cfg.getStringProperty(DB_VALIDATION_QUERY)); 135 } 136 137 144 145 149 private void initialize( 150 String dbDriver, 151 String dbURL, 152 String dbUser, 153 String dbPassword, 154 int maxConnections, 155 String dbValidationQuery) throws SQLException { 156 if (dbURL == null) { 157 throw new SQLException ( 158 "DBPool could not be created: DB URL cannot be null"); 159 } 160 161 if (dbDriver == null) { 162 throw new SQLException ( 163 "DBPool '" + dbURL + "' could not be created: " + 164 "DB driver class name cannot be null!"); 165 } 166 167 if (maxConnections < 0) { 168 throw new SQLException ( 169 "DBPool '" + dbURL + "' could not be created: " + 170 "Max connections must be greater than zero!"); 171 } 172 173 datasource = new BasicDataSource(); 174 datasource.setDriverClassName(dbDriver); 175 datasource.setUrl(dbURL); 176 datasource.setUsername(dbUser); 177 datasource.setPassword(dbPassword); 178 datasource.setMaxActive(maxConnections); 179 if (dbValidationQuery != null) { 180 datasource.setValidationQuery(dbValidationQuery); 181 } 182 } 183 184 192 protected BasicDataSource getDataSource() { 193 return datasource; 194 } 195 196 public Connection getConnection() throws SQLException { 197 return datasource.getConnection(); 198 } 199 200 public void shutdown() throws SQLException { 201 datasource.close(); 202 } 203 } 204 | Popular Tags |