Search in sources :

Example 1 with PooledConnection

use of javax.sql.PooledConnection in project tomcat by apache.

the class CPDSConnectionFactory method doDestroyObject.

private void doDestroyObject(final PooledConnectionAndInfo pci) throws Exception {
    final PooledConnection pc = pci.getPooledConnection();
    pc.removeConnectionEventListener(this);
    pcMap.remove(pc);
    pc.close();
}
Also used : PooledConnection(javax.sql.PooledConnection)

Example 2 with PooledConnection

use of javax.sql.PooledConnection in project tomcat by apache.

the class CPDSConnectionFactory method validateObject.

@Override
public boolean validateObject(final PooledObject<PooledConnectionAndInfo> p) {
    try {
        validateLifetime(p);
    } catch (final Exception e) {
        return false;
    }
    boolean valid = false;
    final PooledConnection pconn = p.getObject().getPooledConnection();
    Connection conn = null;
    validatingSet.add(pconn);
    if (null == _validationQuery) {
        int timeout = _validationQueryTimeout;
        if (timeout < 0) {
            timeout = 0;
        }
        try {
            conn = pconn.getConnection();
            valid = conn.isValid(timeout);
        } catch (final SQLException e) {
            valid = false;
        } finally {
            Utils.closeQuietly(conn);
            validatingSet.remove(pconn);
        }
    } else {
        Statement stmt = null;
        ResultSet rset = null;
        // logical Connection from the PooledConnection must be closed
        // before another one can be requested and closing it will
        // generate an event. Keep track so we know not to return
        // the PooledConnection
        validatingSet.add(pconn);
        try {
            conn = pconn.getConnection();
            stmt = conn.createStatement();
            rset = stmt.executeQuery(_validationQuery);
            if (rset.next()) {
                valid = true;
            } else {
                valid = false;
            }
            if (_rollbackAfterValidation) {
                conn.rollback();
            }
        } catch (final Exception e) {
            valid = false;
        } finally {
            Utils.closeQuietly(rset);
            Utils.closeQuietly(stmt);
            Utils.closeQuietly(conn);
            validatingSet.remove(pconn);
        }
    }
    return valid;
}
Also used : PooledConnection(javax.sql.PooledConnection) SQLException(java.sql.SQLException) Statement(java.sql.Statement) Connection(java.sql.Connection) PooledConnection(javax.sql.PooledConnection) ResultSet(java.sql.ResultSet) SQLException(java.sql.SQLException)

Example 3 with PooledConnection

use of javax.sql.PooledConnection in project tomcat by apache.

the class CPDSConnectionFactory method makeObject.

@Override
public synchronized PooledObject<PooledConnectionAndInfo> makeObject() {
    PooledConnectionAndInfo pci;
    try {
        PooledConnection pc = null;
        if (_username == null) {
            pc = _cpds.getPooledConnection();
        } else {
            pc = _cpds.getPooledConnection(_username, _password);
        }
        if (pc == null) {
            throw new IllegalStateException("Connection pool data source returned null from getPooledConnection");
        }
        // should we add this object as a listener or the pool.
        // consider the validateObject method in decision
        pc.addConnectionEventListener(this);
        pci = new PooledConnectionAndInfo(pc, _username, _password);
        pcMap.put(pc, pci);
    } catch (final SQLException e) {
        throw new RuntimeException(e.getMessage());
    }
    return new DefaultPooledObject<>(pci);
}
Also used : DefaultPooledObject(org.apache.tomcat.dbcp.pool2.impl.DefaultPooledObject) PooledConnection(javax.sql.PooledConnection) SQLException(java.sql.SQLException)

Example 4 with PooledConnection

use of javax.sql.PooledConnection in project tomcat by apache.

the class InstanceKeyDataSource method testCPDS.

protected ConnectionPoolDataSource testCPDS(final String username, final String password) throws javax.naming.NamingException, SQLException {
    // The source of physical db connections
    ConnectionPoolDataSource cpds = this.dataSource;
    if (cpds == null) {
        Context ctx = null;
        if (jndiEnvironment == null) {
            ctx = new InitialContext();
        } else {
            ctx = new InitialContext(jndiEnvironment);
        }
        final Object ds = ctx.lookup(dataSourceName);
        if (ds instanceof ConnectionPoolDataSource) {
            cpds = (ConnectionPoolDataSource) ds;
        } else {
            throw new SQLException("Illegal configuration: " + "DataSource " + dataSourceName + " (" + ds.getClass().getName() + ")" + " doesn't implement javax.sql.ConnectionPoolDataSource");
        }
    }
    // try to get a connection with the supplied username/password
    PooledConnection conn = null;
    try {
        if (username != null) {
            conn = cpds.getPooledConnection(username, password);
        } else {
            conn = cpds.getPooledConnection();
        }
        if (conn == null) {
            throw new SQLException("Cannot connect using the supplied username/password");
        }
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (final SQLException e) {
            // at least we could connect
            }
        }
    }
    return cpds;
}
Also used : ConnectionPoolDataSource(javax.sql.ConnectionPoolDataSource) InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) PooledConnection(javax.sql.PooledConnection) SQLException(java.sql.SQLException) InitialContext(javax.naming.InitialContext)

Example 5 with PooledConnection

use of javax.sql.PooledConnection in project tomcat by apache.

the class InstanceKeyDataSource method getConnection.

/**
     * Attempt to retrieve a database connection using {@link #getPooledConnectionAndInfo(String, String)}
     * with the provided username and password.  The password on the {@link PooledConnectionAndInfo}
     * instance returned by <code>getPooledConnectionAndInfo</code> is compared to the <code>password</code>
     * parameter.  If the comparison fails, a database connection using the supplied username and password
     * is attempted.  If the connection attempt fails, an SQLException is thrown, indicating that the given password
     * did not match the password used to create the pooled connection.  If the connection attempt succeeds, this
     * means that the database password has been changed.  In this case, the <code>PooledConnectionAndInfo</code>
     * instance retrieved with the old password is destroyed and the <code>getPooledConnectionAndInfo</code> is
     * repeatedly invoked until a <code>PooledConnectionAndInfo</code> instance with the new password is returned.
     * @param username The user name to use to connect
     * @param password The password
     * @return the connection
     * @throws SQLException Connection failed
     */
@Override
public Connection getConnection(final String username, final String password) throws SQLException {
    if (instanceKey == null) {
        throw new SQLException("Must set the ConnectionPoolDataSource " + "through setDataSourceName or setConnectionPoolDataSource" + " before calling getConnection.");
    }
    getConnectionCalled = true;
    PooledConnectionAndInfo info = null;
    try {
        info = getPooledConnectionAndInfo(username, password);
    } catch (final NoSuchElementException e) {
        closeDueToException(info);
        throw new SQLException("Cannot borrow connection from pool", e);
    } catch (final RuntimeException e) {
        closeDueToException(info);
        throw e;
    } catch (final SQLException e) {
        closeDueToException(info);
        throw e;
    } catch (final Exception e) {
        closeDueToException(info);
        throw new SQLException("Cannot borrow connection from pool", e);
    }
    if (!(null == password ? null == info.getPassword() : password.equals(info.getPassword()))) {
        // Password on PooledConnectionAndInfo does not match
        try {
            // See if password has changed by attempting connection
            testCPDS(username, password);
        } catch (final SQLException ex) {
            // Password has not changed, so refuse client, but return connection to the pool
            closeDueToException(info);
            throw new SQLException("Given password did not match password used" + " to create the PooledConnection.", ex);
        } catch (final javax.naming.NamingException ne) {
            throw new SQLException("NamingException encountered connecting to database", ne);
        }
        /*
             * Password must have changed -> destroy connection and keep retrying until we get a new, good one,
             * destroying any idle connections with the old password as we pull them from the pool.
             */
        final UserPassKey upkey = info.getUserPassKey();
        final PooledConnectionManager manager = getConnectionManager(upkey);
        // Destroy and remove from pool
        manager.invalidate(info.getPooledConnection());
        // Reset the password on the factory if using CPDSConnectionFactory
        manager.setPassword(upkey.getPassword());
        info = null;
        for (int i = 0; i < 10; i++) {
            // Bound the number of retries - only needed if bad instances return
            try {
                info = getPooledConnectionAndInfo(username, password);
            } catch (final NoSuchElementException e) {
                closeDueToException(info);
                throw new SQLException("Cannot borrow connection from pool", e);
            } catch (final RuntimeException e) {
                closeDueToException(info);
                throw e;
            } catch (final SQLException e) {
                closeDueToException(info);
                throw e;
            } catch (final Exception e) {
                closeDueToException(info);
                throw new SQLException("Cannot borrow connection from pool", e);
            }
            if (info != null && password != null && password.equals(info.getPassword())) {
                break;
            }
            if (info != null) {
                manager.invalidate(info.getPooledConnection());
            }
            info = null;
        }
        if (info == null) {
            throw new SQLException("Cannot borrow connection from pool - password change failure.");
        }
    }
    final Connection con = info.getPooledConnection().getConnection();
    try {
        setupDefaults(con, username);
        con.clearWarnings();
        return con;
    } catch (final SQLException ex) {
        try {
            con.close();
        } catch (final Exception exc) {
            getLogWriter().println("ignoring exception during close: " + exc);
        }
        throw ex;
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) PooledConnection(javax.sql.PooledConnection) NoSuchElementException(java.util.NoSuchElementException) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) SQLException(java.sql.SQLException) NoSuchElementException(java.util.NoSuchElementException)

Aggregations

PooledConnection (javax.sql.PooledConnection)40 SQLException (java.sql.SQLException)21 Connection (java.sql.Connection)14 Test (org.junit.Test)7 Context (javax.naming.Context)4 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)3 ResultSet (java.sql.ResultSet)2 SQLFeatureNotSupportedException (java.sql.SQLFeatureNotSupportedException)2 Statement (java.sql.Statement)2 Iterator (java.util.Iterator)2 XAConnection (javax.sql.XAConnection)2 DefaultPooledObject (org.apache.tomcat.dbcp.pool2.impl.DefaultPooledObject)2 DruidPooledConnection (com.alibaba.druid.pool.DruidPooledConnection)1 PrintWriter (java.io.PrintWriter)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 NoSuchElementException (java.util.NoSuchElementException)1 ReentrantLock (java.util.concurrent.locks.ReentrantLock)1 InitialContext (javax.naming.InitialContext)1 ConnectionPoolDataSource (javax.sql.ConnectionPoolDataSource)1