private PooledConnection createNewConnection() throws SQLException { PooledConnection pooledConnection; // I have changed "size() + 1" to "size()". I don't know why // we would want to report 1 more than the actual pool size, // so I am assuming that this is a coding error. (The size // method does return the actual size of an array). -blaine logInfo("Connection created since no connections available and " + "pool has space for more connections. Pool size: " + size()); pooledConnection = this.connectionPoolDataSource.getPooledConnection(); pooledConnection.addConnectionEventListener(this); return pooledConnection; }
/** * * A fatal error has occurred and the connection cannot be used anymore. * A close event from such a connection should be ignored. The connection should not be reused. * A new connection will be created to replace the invalid connection, when the next client * calls getConnection(). */ public synchronized void connectionErrorOccurred(ConnectionEvent event) { PooledConnection connection = (PooledConnection) event.getSource(); connection.removeConnectionEventListener(this); this.connectionsInUse.remove(connection); this.sessionConnectionWrappers.remove(connection); logInfo( "Fatal exception occurred on pooled connection. Connection is removed from pool: "); logInfo(event.getSQLException()); closePhysically(connection, "closing invalid, removed connection."); //notify threads waiting for connections or for the pool to close. //one waiting thread can now create a new connection since the pool has space for a new connection. //if a thread waits for the pool to close this could be the last unclosed connection in the pool. this.notifyAll(); }
/** * Closes this connection */ public synchronized void closeImmediatedly() { close(); Iterator iterator = this.connectionsInUse.iterator(); while (iterator.hasNext()) { PooledConnection connection = (PooledConnection) iterator.next(); SessionConnectionWrapper sessionWrapper = (SessionConnectionWrapper) this.sessionConnectionWrappers.get( connection); closeSessionWrapper( sessionWrapper, "Error closing session wrapper. Connection pool was shutdown immediatedly."); } }
/** * Retrieves the QueryObjectGenerator for the given JDBC driver. If the * JDBC driver does not provide its own QueryObjectGenerator, NULL is * returned. * @return The QueryObjectGenerator for this JDBC Driver or NULL if the driver does not provide its own * implementation * @exception SQLException if a database access error occurs * @since JDK 1.6, HSQLDB 1.8.x */ //#ifdef JAVA6BETA /* public QueryObjectGenerator getQueryObjectGenerator() throws SQLException { return null; } */ //#endif JAVA6BETA // ------------------------ internal implementation ------------------------ private PooledConnection createPooledConnection(JDBCConnection connection) throws SQLException { LifeTimeConnectionWrapper connectionWrapper = new LifeTimeConnectionWrapper(connection, this.connectionDefaults); JDBCPooledConnection pooledConnection = new JDBCPooledConnection(connectionWrapper); connectionWrapper.setPooledConnection(pooledConnection); return pooledConnection; }
/** * Tests fix for BUG#62452 - NPE thrown in JDBC4MySQLPooledException when statement is closed. * * @throws Exception */ public void testBug62452() throws Exception { PooledConnection con = null; MysqlConnectionPoolDataSource pds = new MysqlConnectionPoolDataSource(); pds.setUrl(dbUrl); con = pds.getPooledConnection(); assertTrue(con instanceof JDBC4MysqlPooledConnection); testBug62452WithConnection(con); MysqlXADataSource xads = new MysqlXADataSource(); xads.setUrl(dbUrl); xads.setPinGlobalTxToPhysicalConnection(false); con = xads.getXAConnection(); assertTrue(con instanceof JDBC4MysqlXAConnection); testBug62452WithConnection(con); xads.setPinGlobalTxToPhysicalConnection(true); con = xads.getXAConnection(); assertTrue(con instanceof JDBC4SuspendableXAConnection); testBug62452WithConnection(con); }
@TestFactory public Stream<DynamicTest> queryTable() throws SQLException { List<ChangeKey> changeCaptureTables = new ArrayList<>(); PooledConnection pooledConnection = null; try { pooledConnection = JdbcUtils.openPooledConnection(this.config, new ChangeKey(MsSqlTestConstants.DATABASE_NAME, null, null)); MsSqlQueryBuilder queryBuilder = new MsSqlQueryBuilder(pooledConnection.getConnection()); try (PreparedStatement statement = queryBuilder.listChangeTrackingTablesStatement()) { try (ResultSet resultSet = statement.executeQuery()) { while (resultSet.next()) { String databaseName = resultSet.getString("databaseName"); String schemaName = resultSet.getString("schemaName"); String tableName = resultSet.getString("tableName"); ChangeKey changeKey = new ChangeKey(databaseName, schemaName, tableName); changeCaptureTables.add(changeKey); log.trace("Found Change Tracking Enabled Table {}", changeKey); } } } } finally { JdbcUtils.closeConnection(pooledConnection); } return changeCaptureTables.stream().map(data -> dynamicTest(data.tableName, () -> queryTable(data))); }
/** * Constructs a MiniConnectionPoolManager object. * * @param dataSource the data source for the connections. * @param maxConnections the maximum number of connections. * @param timeout the maximum time in seconds to wait for a free connection. */ public MiniConnectionPoolManager(ConnectionPoolDataSource dataSource, int maxConnections, int timeout) { this.dataSource = dataSource; this.maxConnections = maxConnections; this.timeoutMs = timeout * 1000L; try { logWriter = dataSource.getLogWriter(); } catch (SQLException e) { } if (maxConnections < 1) { throw new IllegalArgumentException("Invalid maxConnections value."); } semaphore = new Semaphore(maxConnections, true); recycledConnections = new LinkedList<PooledConnection>(); poolConnectionEventListener = new PoolConnectionEventListener(); }
/** * Closes all unused pooled connections. */ public synchronized void dispose() throws SQLException { if (isDisposed) { return; } isDisposed = true; SQLException e = null; while (!recycledConnections.isEmpty()) { PooledConnection pconn = recycledConnections.remove(); try { pconn.close(); } catch (SQLException e2) { if (e == null) { e = e2; } } } if (e != null) { throw e; } }
private synchronized Connection getConnection3() throws SQLException { if (isDisposed) { // test again within synchronized lock throw new IllegalStateException("Connection pool has been disposed."); } PooledConnection pconn; if (!recycledConnections.isEmpty()) { pconn = recycledConnections.remove(); } else { pconn = dataSource.getPooledConnection(); pconn.addConnectionEventListener(poolConnectionEventListener); } Connection conn; try { // The JDBC driver may call ConnectionEventListener.connectionErrorOccurred() // from within PooledConnection.getConnection(). To detect this within // disposeConnection(), we temporarily set connectionInTransition. connectionInTransition = pconn; conn = pconn.getConnection(); } finally { connectionInTransition = null; } activeConnections++; assertInnerState(); return conn; }
private synchronized void recycleConnection(PooledConnection pconn) { if (isDisposed || doPurgeConnection) { disposeConnection(pconn); return; } if (pconn == connectionInTransition) { // This happens when a faulty JDBC driver calls ConnectionEventListener.connectionClosed() // a second time within PooledConnection.getConnection(). return; } if (activeConnections <= 0) { throw new AssertionError(); } activeConnections--; semaphore.release(); recycledConnections.add(pconn); assertInnerState(); }
/** * Implementation of call back function from ConnectionEventListener interface. This callback will * be invoked on connection error event. * * @param event */ public void connectionErrorOccurred(ConnectionEvent event) { if (isActive) { try { PooledConnection conn = (PooledConnection) event.getSource(); provider.returnAndExpireConnection(conn); } catch (Exception ex) { String exception = "GemFireConnPooledDataSource::connectionErrorOccured:error in returning and expiring connection due to " + ex; if (logger.isDebugEnabled()) { logger.debug(exception, ex); } } } }
/** * Creates a new connection for the pool. This connection can participate in the transactions. * * @return the connection from the database as PooledConnection object. */ @Override public Object getNewPoolConnection() throws PoolException { if (m_xads != null) { PooledConnection poolConn = null; try { poolConn = m_xads.getXAConnection(configProps.getUser(), configProps.getPassword()); } catch (SQLException sqx) { throw new PoolException( LocalizedStrings.TranxPoolCacheImpl_TRANXPOOLCACHEIMPLGETNEWCONNECTION_EXCEPTION_IN_CREATING_NEW_TRANSACTION_POOLEDCONNECTION .toLocalizedString(), sqx); } poolConn.addConnectionEventListener((javax.sql.ConnectionEventListener) connEventListner); return poolConn; } else { if (logger.isDebugEnabled()) { logger.debug( "TranxPoolCacheImpl::getNewConnection: ConnectionPoolCache not intialized with XADatasource"); } throw new PoolException( LocalizedStrings.TranxPoolCacheImpl_TRANXPOOLCACHEIMPLGETNEWCONNECTION_CONNECTIONPOOLCACHE_NOT_INTIALIZED_WITH_XADATASOURCE .toLocalizedString()); } }
/** * Creates a new connection for the pool. * * @return the connection from the database as Object. * @throws PoolException */ @Override public Object getNewPoolConnection() throws PoolException { if (m_cpds != null) { PooledConnection poolConn = null; try { poolConn = m_cpds.getPooledConnection(configProps.getUser(), configProps.getPassword()); } catch (SQLException sqx) { throw new PoolException( LocalizedStrings.ConnectionPoolCacheImpl_CONNECTIONPOOLCACHEIMPLGENEWCONNECTION_EXCEPTION_IN_CREATING_NEW_POOLEDCONNECTION .toLocalizedString(), sqx); } poolConn.addConnectionEventListener((javax.sql.ConnectionEventListener) connEventListner); return poolConn; } else { if (logger.isDebugEnabled()) { logger.debug( "ConnectionPoolCacheImpl::geNewConnection: ConnectionPoolCache not intialized with ConnectionPoolDatasource"); } throw new PoolException( LocalizedStrings.ConnectionPoolCacheImpl_CONNECTIONPOOLCACHEIMPLGENEWCONNECTION_CONNECTIONPOOLCACHE_NOT_INTIALIZED_WITH_CONNECTIONPOOLDATASOURCE .toLocalizedString()); } }
public void run() { String threadName = Thread.currentThread().getName(); // System.out.println(" Inside Run method of " + threadName); int numConn2 = 0; // int display = 0; while (numConn2 < maxPoolSize) { try { PooledConnection conn = (PooledConnection) poolCache.getPooledConnectionFromPool(); poolConnlist.add(conn); numConn2++; // System.out.println(" ********** Got connection " + numConn2+ "from // " + threadName); } catch (Exception ex) { fail("Exception occured in trying to getPooledConnectionFromPool due to " + ex); ex.printStackTrace(); } } if (numConn2 != maxPoolSize) fail("#### Error in getting all connections from the " + threadName); // System.out.println(" ****************GOT ALL connections "+ threadName // + "***********"); }
/** * Test of returnPooledConnectionToPool method, of class * org.apache.geode.internal.datasource.AbstractPoolCache. */ @Test public void testReturnPooledConnectionToPool() throws Exception { Context ctx = cache.getJNDIContext(); GemFireConnPooledDataSource ds = (GemFireConnPooledDataSource) ctx.lookup("java:/PooledDataSource"); GemFireConnectionPoolManager provider = (GemFireConnectionPoolManager) ds.getConnectionProvider(); ConnectionPoolCacheImpl poolCache = (ConnectionPoolCacheImpl) provider.getConnectionPoolCache(); PooledConnection conn = (PooledConnection) poolCache.getPooledConnectionFromPool(); if (poolCache.availableCache.containsKey(conn)) fail("connection not removed from available cache list"); if (!poolCache.activeCache.containsKey(conn)) fail("connection not put in active connection list"); provider.returnConnection(conn); if (!poolCache.availableCache.containsKey(conn)) fail("connection not returned to pool"); if (poolCache.activeCache.containsKey(conn)) fail("connection not returned to active list"); }
public void connectionClosed(ConnectionEvent event) { PooledConnection connection = (PooledConnection) event.getSource(); for (int i = 0; i < connections.length; i++) { if (connections[i] == connection) { states.set(i, RefState.available); break; } } }
/** * Dequeues first available connection if any. If no available connections it returns null. * @return The first available connection if any. Null if no connections are available. */ private PooledConnection dequeueFirstIfAny() { if (this.connectionsInactive.size() <= 0) { return null; } return (PooledConnection) this.connectionsInactive.remove(0); }
private PooledConnection assureValidConnection( PooledConnection pooledConnection) throws SQLException { if (isInvalid(pooledConnection)) { closePhysically(pooledConnection, "closing invalid pooledConnection."); return this.connectionPoolDataSource.getPooledConnection(); } return pooledConnection; }
private boolean isInvalid(PooledConnection pooledConnection) { /** @todo: add || pooledConnection.getConnection.isValid() when JDBC 4.0 arrives. */ try { return pooledConnection.getConnection().isClosed(); } catch (SQLException e) { logInfo( "Error calling pooledConnection.getConnection().isClosed(). Connection will be removed from pool.", e); return false; } }
public synchronized void connectionClosed(ConnectionEvent event) { PooledConnection connection = (PooledConnection) event.getSource(); this.connectionsInUse.remove(connection); this.sessionConnectionWrappers.remove(connection); if (!this.isPoolClosed) { enqueue(connection); logInfo("Connection returned to pool."); } else { closePhysically(connection, "closing returned connection."); logInfo( "Connection returned to pool was closed because pool is closed."); this.notifyAll(); //notifies evt. threads waiting for connection or for the pool to close. } }
/** * Closes this connection pool. No further connections can be obtained from it after this. * All inactive connections are physically closed before the call returns. * Active connections are not closed. * There may still be active connections in use after this method returns. * When these connections are closed and returned to the pool they will be * physically closed. */ public synchronized void close() { this.isPoolClosed = true; while (this.connectionsInactive.size() > 0) { PooledConnection connection = dequeueFirstIfAny(); if (connection != null) { closePhysically( connection, "closing inactive connection when connection pool was closed."); } } }
/** * Tests fix for BUG#4808- Calling .close() twice on a PooledConnection * causes NPE. * * @throws Exception * if an error occurs. */ public void testBug4808() throws Exception { MysqlConnectionPoolDataSource ds = new MysqlConnectionPoolDataSource(); ds.setURL(BaseTestCase.dbUrl); PooledConnection closeMeTwice = ds.getPooledConnection(); closeMeTwice.close(); closeMeTwice.close(); }
/** * Tests fix for BUG#32101 - When using a connection from our ConnectionPoolDataSource, * some Connection.prepareStatement() methods would return null instead of * a prepared statement. * * @throws Exception */ public void testBug32101() throws Exception { MysqlConnectionPoolDataSource ds = new MysqlConnectionPoolDataSource(); ds.setURL(BaseTestCase.dbUrl); PooledConnection pc = ds.getPooledConnection(); assertNotNull(pc.getConnection().prepareStatement("SELECT 1")); assertNotNull(pc.getConnection().prepareStatement("SELECT 1", Statement.RETURN_GENERATED_KEYS)); assertNotNull(pc.getConnection().prepareStatement("SELECT 1", new int[0])); assertNotNull(pc.getConnection().prepareStatement("SELECT 1", new String[0])); assertNotNull(pc.getConnection().prepareStatement("SELECT 1", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)); assertNotNull( pc.getConnection().prepareStatement("SELECT 1", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT)); }
public PooledConnection getPooledConnection(String user, String password) throws SQLException { throw new SQLException( "Use the getXAConnections to get XA Connections.\n" + "Use the class JDBCConnectionPoolDataSource for non-XA data sources."); }
@Test public void testGetConnection() throws Exception { Connection con = this.datasource.getConnection(); Assert.assertTrue("Connection should implement javax.sql.PooledConnection",con instanceof PooledConnection); Connection actual = ((PooledConnection)con).getConnection(); Assert.assertNotNull("Connection delegate should not be null.",actual); System.out.println("Actual connection:"+actual.getClass().getName()); }
private void testBug62452WithConnection(PooledConnection con) throws Exception { this.pstmt = con.getConnection().prepareStatement("SELECT 1"); this.rs = this.pstmt.executeQuery(); con.close(); // If PooledConnection is already closed by some reason a NullPointerException was thrown on the next line // because the closed connection has nulled out the list that it synchronises on when the closed event is fired. this.pstmt.close(); }
/** * Tests that PacketTooLargeException doesn't clober the connection. * * @throws Exception * if the test fails. */ public void testPacketTooLargeException() throws Exception { final ConnectionEventListener conListener = new ConnectionListener(); PooledConnection pc = null; pc = this.cpds.getPooledConnection(); pc.addConnectionEventListener(conListener); createTable("testPacketTooLarge", "(field1 LONGBLOB)"); Connection connFromPool = pc.getConnection(); PreparedStatement pstmtFromPool = ((ConnectionWrapper) connFromPool).clientPrepare("INSERT INTO testPacketTooLarge VALUES (?)"); this.rs = this.stmt.executeQuery("SHOW VARIABLES LIKE 'max_allowed_packet'"); this.rs.next(); int maxAllowedPacket = this.rs.getInt(2); int numChars = (int) (maxAllowedPacket * 1.2); pstmtFromPool.setBinaryStream(1, new BufferedInputStream(new FileInputStream(newTempBinaryFile("testPacketTooLargeException", numChars))), numChars); try { pstmtFromPool.executeUpdate(); fail("Expecting PacketTooLargeException"); } catch (PacketTooBigException ptbe) { // We're expecting this one... } // This should still work okay, even though the last query on the same connection didn't... this.rs = connFromPool.createStatement().executeQuery("SELECT 1"); assertTrue(this.connectionErrorEventCount == 0); assertTrue(this.closeEventCount == 0); }
@Override protected TableMetadata fetchTableMetadata(ChangeKey changeKey) throws SQLException { log.info("{}: querying database for metadata.", changeKey); PooledConnection pooledConnection = null; try { pooledConnection = JdbcUtils.openPooledConnection(this.config, changeKey); log.trace("{}: Querying for primary keys.", changeKey); Set<String> keyColumns = new LinkedHashSet<>(); try (PreparedStatement primaryKeyStatement = pooledConnection.getConnection().prepareStatement(PRIMARY_KEY_SQL)) { primaryKeyStatement.setString(1, changeKey.schemaName); primaryKeyStatement.setString(2, changeKey.tableName); try (ResultSet resultSet = primaryKeyStatement.executeQuery()) { while (resultSet.next()) { keyColumns.add(resultSet.getString(1)); } } } log.trace("{}: Querying for schema.", changeKey); Map<String, Schema> columnSchemas = new LinkedHashMap<>(); try (PreparedStatement columnDefinitionStatement = pooledConnection.getConnection().prepareStatement(COLUMN_DEFINITION_SQL)) { columnDefinitionStatement.setString(1, changeKey.schemaName); columnDefinitionStatement.setString(2, changeKey.tableName); try (ResultSet resultSet = columnDefinitionStatement.executeQuery()) { while (resultSet.next()) { String columnName = resultSet.getString(1); Schema schema = generateSchema(resultSet, changeKey, columnName); columnSchemas.put(columnName, schema); } } } return new MsSqlTableMetadata(changeKey, keyColumns, columnSchemas); } finally { JdbcUtils.closeConnection(pooledConnection); } }
public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo connectionRequestInfo) throws ResourceException { CredentialExtractor credentialExtractor = new CredentialExtractor(subject, connectionRequestInfo, this); PooledConnection sqlConnection = getPhysicalConnection(credentialExtractor); try { Connection pc = wrap(sqlConnection.getConnection()); return new ManagedPooledConnection(this, sqlConnection, pc, credentialExtractor, exceptionSorter); } catch (SQLException e) { throw new ResourceAdapterInternalException("Could not set up ManagedPooledConnection", e); } }
protected PooledConnection getPhysicalConnection(CredentialExtractor credentialExtractor) throws ResourceException { try { String username = credentialExtractor.getUserName(); String password = credentialExtractor.getPassword(); if (username != null) { return dataSource.getPooledConnection(username, password); } else { return dataSource.getPooledConnection(); } } catch (SQLException e) { throw new ResourceAdapterInternalException("Unable to obtain physical connection to " + dataSource, e); } }