1 56 57 package org.objectstyle.cayenne.conn; 58 59 import java.io.PrintWriter ; 60 import java.sql.Connection ; 61 import java.sql.Driver ; 62 import java.sql.DriverManager ; 63 import java.sql.SQLException ; 64 import java.util.Properties ; 65 66 import javax.sql.DataSource ; 67 68 73 public class DriverDataSource implements DataSource { 74 75 protected Driver driver; 76 77 protected String connectionUrl; 78 protected String userName; 79 protected String password; 80 81 protected ConnectionEventLoggingDelegate logger; 82 83 86 public DriverDataSource(String driverClassName, String connectionUrl) 87 throws SQLException { 88 89 this.connectionUrl = connectionUrl; 90 91 if (driverClassName != null) { 92 try { 93 this.driver = (Driver ) Class.forName(driverClassName).newInstance(); 94 } 95 catch (Exception ex) { 96 throw new SQLException ("Can not load JDBC driver named '" 97 + driverClassName 98 + "': " 99 + ex.getMessage()); 100 } 101 } 102 } 103 104 109 public DriverDataSource(Driver driver, String connectionUrl, String userName, 110 String password) { 111 this.driver = driver; 112 this.connectionUrl = connectionUrl; 113 this.userName = userName; 114 this.password = password; 115 } 116 117 121 public Connection getConnection() throws SQLException { 122 return getConnection(userName, password); 124 } 125 126 130 public Connection getConnection(String userName, String password) throws SQLException { 131 try { 132 if (logger != null) { 133 logger.logConnect(connectionUrl, userName, password); 134 } 135 136 Connection c = null; 137 138 if (driver == null) { 139 c = DriverManager.getConnection(connectionUrl, userName, password); 140 } 141 else { 142 Properties connectProperties = new Properties (); 143 144 if (userName != null) { 145 connectProperties.put("user", userName); 146 } 147 148 if (password != null) { 149 connectProperties.put("password", password); 150 } 151 c = driver.connect(connectionUrl, connectProperties); 152 } 153 154 157 if (c == null) { 158 throw new SQLException ("Can't establish connection: " + connectionUrl); 159 } 160 161 if (logger != null) { 162 logger.logConnectSuccess(); 163 } 164 165 return c; 166 } 167 catch (SQLException sqlex) { 168 if (logger != null) { 169 logger.logConnectFailure(sqlex); 170 } 171 172 throw sqlex; 173 } 174 } 175 176 public int getLoginTimeout() throws SQLException { 177 return -1; 178 } 179 180 public void setLoginTimeout(int seconds) throws SQLException { 181 } 183 184 public PrintWriter getLogWriter() throws SQLException { 185 return DriverManager.getLogWriter(); 186 } 187 188 public void setLogWriter(PrintWriter out) throws SQLException { 189 DriverManager.setLogWriter(out); 190 } 191 192 public ConnectionEventLoggingDelegate getLogger() { 193 return logger; 194 } 195 196 public void setLogger(ConnectionEventLoggingDelegate delegate) { 197 logger = delegate; 198 } 199 } | Popular Tags |