1 19 package com.mysql.jdbc.jdbc2.optional; 20 21 import java.sql.Connection ; 22 import java.sql.SQLException ; 23 24 import java.util.Enumeration ; 25 import java.util.Hashtable ; 26 27 import javax.sql.ConnectionEvent ; 28 import javax.sql.ConnectionEventListener ; 29 import javax.sql.PooledConnection ; 30 31 32 40 public class MysqlPooledConnection 41 implements PooledConnection { 42 43 46 public static final int CONNECTION_ERROR_EVENT = 1; 47 48 51 public static final int CONNECTION_CLOSED_EVENT = 2; 52 53 55 private Hashtable eventListeners; 56 private Connection logicalHandle; 57 private Connection physicalConn; 58 59 60 62 67 public MysqlPooledConnection(Connection connection) { 68 logicalHandle = null; 69 physicalConn = connection; 70 eventListeners = new Hashtable (10); 71 } 72 73 75 81 public synchronized void addConnectionEventListener(ConnectionEventListener connectioneventlistener) { 82 83 if (eventListeners != null) { 84 eventListeners.put(connectioneventlistener, 85 connectioneventlistener); 86 } 87 } 88 89 95 public synchronized void removeConnectionEventListener(ConnectionEventListener connectioneventlistener) { 96 97 if (eventListeners != null) { 98 eventListeners.remove(connectioneventlistener); 99 } 100 } 101 102 108 public synchronized Connection getConnection() 109 throws SQLException { 110 111 if (physicalConn == null) { 112 113 SQLException sqlException = new SQLException ( 114 "Physical Connection doesn't exist"); 115 callListener(CONNECTION_ERROR_EVENT, sqlException); 116 117 return null; 118 } 119 120 try { 121 122 if (logicalHandle != null) { 123 ((ConnectionWrapper)logicalHandle).close(false); 124 } 125 126 logicalHandle = new ConnectionWrapper(this, physicalConn); 127 } catch (SQLException sqlException) { 128 callListener(CONNECTION_ERROR_EVENT, sqlException); 129 130 return null; 131 } 132 133 return logicalHandle; 134 } 135 136 143 public synchronized void close() 144 throws SQLException { 145 physicalConn.close(); 146 physicalConn = null; 147 } 148 149 157 protected synchronized void callListener(int eventType, SQLException sqlException) { 158 159 if (eventListeners == null) { 160 161 return; 162 } 163 164 Enumeration enumeration = eventListeners.keys(); 165 ConnectionEvent connectionevent = new ConnectionEvent (this, 166 sqlException); 167 168 while (enumeration.hasMoreElements()) { 169 170 ConnectionEventListener connectioneventlistener = 171 (ConnectionEventListener ) enumeration.nextElement(); 172 ConnectionEventListener connectioneventlistener1 = 173 (ConnectionEventListener ) eventListeners.get( 174 connectioneventlistener); 175 176 if (eventType == CONNECTION_CLOSED_EVENT) { 177 connectioneventlistener1.connectionClosed(connectionevent); 178 } else if (eventType == CONNECTION_ERROR_EVENT) { 179 connectioneventlistener1.connectionErrorOccurred( 180 connectionevent); 181 } 182 } 183 } 184 } | Popular Tags |