Class InstanceKeyDataSource

  • All Implemented Interfaces:
    java.io.Serializable, java.sql.Wrapper, javax.naming.Referenceable, javax.sql.CommonDataSource, javax.sql.DataSource
    Direct Known Subclasses:
    PerUserPoolDataSource, SharedPoolDataSource

    public abstract class InstanceKeyDataSource
    extends java.lang.Object
    implements javax.sql.DataSource, javax.naming.Referenceable, java.io.Serializable

    The base class for SharedPoolDataSource and PerUserPoolDataSource. Many of the configuration properties are shared and defined here. This class is declared public in order to allow particular usage with commons-beanutils; do not make direct use of it outside of commons-dbcp.

    A J2EE container will normally provide some method of initializing the DataSource whose attributes are presented as bean getters/setters and then deploying it via JNDI. It is then available to an application as a source of pooled logical connections to the database. The pool needs a source of physical connections. This source is in the form of a ConnectionPoolDataSource that can be specified via the setDataSourceName(String) used to lookup the source via JNDI.

    Although normally used within a JNDI environment, A DataSource can be instantiated and initialized as any bean. In this case the ConnectionPoolDataSource will likely be instantiated in a similar manner. This class allows the physical source of connections to be attached directly to this pool using the setConnectionPoolDataSource(ConnectionPoolDataSource) method.

    The dbcp package contains an adapter, DriverAdapterCPDS, that can be used to allow the use of DataSource's based on this class with jdbc driver implementations that do not supply a ConnectionPoolDataSource, but still provide a Driver implementation.

    The package documentation contains an example using Apache Tomcat and JNDI and it also contains a non-JNDI example.

    Version:
    $Revision: 907428 $ $Date: 2010-02-07 09:59:08 -0500 (Sun, 07 Feb 2010) $
    Author:
    John D. McNally
    See Also:
    Serialized Form
    • Field Summary

      Fields 
      Modifier and Type Field Description
      protected java.lang.String instanceKey
      Instance key
      protected static int UNKNOWN_TRANSACTIONISOLATION
      Internal constant to indicate the level is not set.
    • Constructor Summary

      Constructors 
      Constructor Description
      InstanceKeyDataSource()
      Default no-arg constructor for Serialization
    • Method Summary

      All Methods Instance Methods Abstract Methods Concrete Methods 
      Modifier and Type Method Description
      protected void assertInitializationAllowed()
      Throws an IllegalStateException, if a PooledConnection has already been requested.
      abstract void close()
      Close the connection pool being maintained by this datasource.
      java.sql.Connection getConnection()
      Attempt to establish a database connection.
      java.sql.Connection getConnection​(java.lang.String username, java.lang.String password)
      Attempt to retrieve a database connection using getPooledConnectionAndInfo(String, String) with the provided username and password.
      protected abstract org.apache.commons.dbcp.datasources.PooledConnectionManager getConnectionManager​(org.apache.commons.dbcp.datasources.UserPassKey upkey)  
      javax.sql.ConnectionPoolDataSource getConnectionPoolDataSource()
      Get the value of connectionPoolDataSource.
      java.lang.String getDataSourceName()
      Get the name of the ConnectionPoolDataSource which backs this pool.
      int getDefaultTransactionIsolation()
      Get the value of defaultTransactionIsolation, which defines the state of connections handed out from this pool.
      java.lang.String getDescription()
      Get the description.
      java.lang.String getJndiEnvironment​(java.lang.String key)
      Get the value of jndiEnvironment which is used when instantiating a jndi InitialContext.
      int getLoginTimeout()
      Get the value of loginTimeout.
      java.io.PrintWriter getLogWriter()
      Get the value of logWriter.
      int getMinEvictableIdleTimeMillis()
      Returns the minimum amount of time an object may sit idle in the pool before it is eligable for eviction by the idle object evictor (if any).
      int getNumTestsPerEvictionRun()
      Returns the number of objects to examine during each run of the idle object evictor thread (if any).
      protected abstract org.apache.commons.dbcp.datasources.PooledConnectionAndInfo getPooledConnectionAndInfo​(java.lang.String username, java.lang.String password)  
      javax.naming.Reference getReference()
      Retrieves the Reference of this object.
      boolean getTestOnBorrow()
      When true, objects will be {*link PoolableObjectFactory#validateObject validated} before being returned by the {*link #borrowObject} method.
      boolean getTestOnReturn()
      When true, objects will be {*link PoolableObjectFactory#validateObject validated} before being returned to the pool within the {*link #returnObject}.
      boolean getTestWhileIdle()
      When true, objects will be {*link PoolableObjectFactory#validateObject validated} by the idle object evictor (if any).
      int getTimeBetweenEvictionRunsMillis()
      Returns the number of milliseconds to sleep between runs of the idle object evictor thread.
      java.lang.String getValidationQuery()
      The SQL query that will be used to validate connections from this pool before returning them to the caller.
      boolean isDefaultAutoCommit()
      Get the value of defaultAutoCommit, which defines the state of connections handed out from this pool.
      boolean isDefaultReadOnly()
      Get the value of defaultReadOnly, which defines the state of connections handed out from this pool.
      boolean isRollbackAfterValidation()
      Whether a rollback will be issued after executing the SQL query that will be used to validate connections from this pool before returning them to the caller.
      boolean isTestOnBorrow()  
      boolean isTestOnReturn()  
      boolean isTestWhileIdle()  
      boolean isWrapperFor​(java.lang.Class<?> iface)  
      void setConnectionPoolDataSource​(javax.sql.ConnectionPoolDataSource v)
      Set the backend ConnectionPoolDataSource.
      void setDataSourceName​(java.lang.String v)
      Set the name of the ConnectionPoolDataSource which backs this pool.
      void setDefaultAutoCommit​(boolean v)
      Set the value of defaultAutoCommit, which defines the state of connections handed out from this pool.
      void setDefaultReadOnly​(boolean v)
      Set the value of defaultReadOnly, which defines the state of connections handed out from this pool.
      void setDefaultTransactionIsolation​(int v)
      Set the value of defaultTransactionIsolation, which defines the state of connections handed out from this pool.
      void setDescription​(java.lang.String v)
      Set the description.
      void setJndiEnvironment​(java.lang.String key, java.lang.String value)
      Sets the value of the given JNDI environment property to be used when instantiating a JNDI InitialContext.
      void setLoginTimeout​(int v)
      Set the value of loginTimeout.
      void setLogWriter​(java.io.PrintWriter v)
      Set the value of logWriter.
      void setMinEvictableIdleTimeMillis​(int minEvictableIdleTimeMillis)
      Sets the minimum amount of time an object may sit idle in the pool before it is eligable for eviction by the idle object evictor (if any).
      void setNumTestsPerEvictionRun​(int numTestsPerEvictionRun)
      Sets the number of objects to examine during each run of the idle object evictor thread (if any).
      void setRollbackAfterValidation​(boolean rollbackAfterValidation)
      Whether a rollback will be issued after executing the SQL query that will be used to validate connections from this pool before returning them to the caller.
      void setTestOnBorrow​(boolean testOnBorrow)
      When true, objects will be {*link PoolableObjectFactory#validateObject validated} before being returned by the {*link #borrowObject} method.
      void setTestOnReturn​(boolean testOnReturn)
      When true, objects will be {*link PoolableObjectFactory#validateObject validated} before being returned to the pool within the {*link #returnObject}.
      void setTestWhileIdle​(boolean testWhileIdle)
      When true, objects will be {*link PoolableObjectFactory#validateObject validated} by the idle object evictor (if any).
      void setTimeBetweenEvictionRunsMillis​(int timeBetweenEvictionRunsMillis)
      Sets the number of milliseconds to sleep between runs of the idle object evictor thread.
      protected abstract void setupDefaults​(java.sql.Connection con, java.lang.String username)  
      void setValidationQuery​(java.lang.String validationQuery)
      The SQL query that will be used to validate connections from this pool before returning them to the caller.
      protected javax.sql.ConnectionPoolDataSource testCPDS​(java.lang.String username, java.lang.String password)  
      <T> T unwrap​(java.lang.Class<T> iface)  
      protected byte whenExhaustedAction​(int maxActive, int maxWait)  
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
      • Methods inherited from interface javax.sql.CommonDataSource

        createShardingKeyBuilder, getParentLogger
      • Methods inherited from interface javax.sql.DataSource

        createConnectionBuilder
    • Field Detail

      • UNKNOWN_TRANSACTIONISOLATION

        protected static final int UNKNOWN_TRANSACTIONISOLATION
        Internal constant to indicate the level is not set.
        See Also:
        Constant Field Values
      • instanceKey

        protected java.lang.String instanceKey
        Instance key
    • Constructor Detail

      • InstanceKeyDataSource

        public InstanceKeyDataSource()
        Default no-arg constructor for Serialization
    • Method Detail

      • assertInitializationAllowed

        protected void assertInitializationAllowed()
                                            throws java.lang.IllegalStateException
        Throws an IllegalStateException, if a PooledConnection has already been requested.
        Throws:
        java.lang.IllegalStateException
      • close

        public abstract void close()
                            throws java.lang.Exception
        Close the connection pool being maintained by this datasource.
        Throws:
        java.lang.Exception
      • getConnectionManager

        protected abstract org.apache.commons.dbcp.datasources.PooledConnectionManager getConnectionManager​(org.apache.commons.dbcp.datasources.UserPassKey upkey)
      • isWrapperFor

        public boolean isWrapperFor​(java.lang.Class<?> iface)
                             throws java.sql.SQLException
        Specified by:
        isWrapperFor in interface java.sql.Wrapper
        Throws:
        java.sql.SQLException
      • unwrap

        public <T> T unwrap​(java.lang.Class<T> iface)
                     throws java.sql.SQLException
        Specified by:
        unwrap in interface java.sql.Wrapper
        Throws:
        java.sql.SQLException
      • getConnectionPoolDataSource

        public javax.sql.ConnectionPoolDataSource getConnectionPoolDataSource()
        Get the value of connectionPoolDataSource. This method will return null, if the backing datasource is being accessed via jndi.
        Returns:
        value of connectionPoolDataSource.
      • setConnectionPoolDataSource

        public void setConnectionPoolDataSource​(javax.sql.ConnectionPoolDataSource v)
        Set the backend ConnectionPoolDataSource. This property should not be set if using jndi to access the datasource.
        Parameters:
        v - Value to assign to connectionPoolDataSource.
      • getDataSourceName

        public java.lang.String getDataSourceName()
        Get the name of the ConnectionPoolDataSource which backs this pool. This name is used to look up the datasource from a jndi service provider.
        Returns:
        value of dataSourceName.
      • setDataSourceName

        public void setDataSourceName​(java.lang.String v)
        Set the name of the ConnectionPoolDataSource which backs this pool. This name is used to look up the datasource from a jndi service provider.
        Parameters:
        v - Value to assign to dataSourceName.
      • isDefaultAutoCommit

        public boolean isDefaultAutoCommit()
        Get the value of defaultAutoCommit, which defines the state of connections handed out from this pool. The value can be changed on the Connection using Connection.setAutoCommit(boolean). The default is true.
        Returns:
        value of defaultAutoCommit.
      • setDefaultAutoCommit

        public void setDefaultAutoCommit​(boolean v)
        Set the value of defaultAutoCommit, which defines the state of connections handed out from this pool. The value can be changed on the Connection using Connection.setAutoCommit(boolean). The default is true.
        Parameters:
        v - Value to assign to defaultAutoCommit.
      • isDefaultReadOnly

        public boolean isDefaultReadOnly()
        Get the value of defaultReadOnly, which defines the state of connections handed out from this pool. The value can be changed on the Connection using Connection.setReadOnly(boolean). The default is false.
        Returns:
        value of defaultReadOnly.
      • setDefaultReadOnly

        public void setDefaultReadOnly​(boolean v)
        Set the value of defaultReadOnly, which defines the state of connections handed out from this pool. The value can be changed on the Connection using Connection.setReadOnly(boolean). The default is false.
        Parameters:
        v - Value to assign to defaultReadOnly.
      • getDefaultTransactionIsolation

        public int getDefaultTransactionIsolation()
        Get the value of defaultTransactionIsolation, which defines the state of connections handed out from this pool. The value can be changed on the Connection using Connection.setTransactionIsolation(int). If this method returns -1, the default is JDBC driver dependent.
        Returns:
        value of defaultTransactionIsolation.
      • setDefaultTransactionIsolation

        public void setDefaultTransactionIsolation​(int v)
        Set the value of defaultTransactionIsolation, which defines the state of connections handed out from this pool. The value can be changed on the Connection using Connection.setTransactionIsolation(int). The default is JDBC driver dependent.
        Parameters:
        v - Value to assign to defaultTransactionIsolation
      • getDescription

        public java.lang.String getDescription()
        Get the description. This property is defined by jdbc as for use with GUI (or other) tools that might deploy the datasource. It serves no internal purpose.
        Returns:
        value of description.
      • setDescription

        public void setDescription​(java.lang.String v)
        Set the description. This property is defined by jdbc as for use with GUI (or other) tools that might deploy the datasource. It serves no internal purpose.
        Parameters:
        v - Value to assign to description.
      • getJndiEnvironment

        public java.lang.String getJndiEnvironment​(java.lang.String key)
        Get the value of jndiEnvironment which is used when instantiating a jndi InitialContext. This InitialContext is used to locate the backend ConnectionPoolDataSource.
        Returns:
        value of jndiEnvironment.
      • setJndiEnvironment

        public void setJndiEnvironment​(java.lang.String key,
                                       java.lang.String value)
        Sets the value of the given JNDI environment property to be used when instantiating a JNDI InitialContext. This InitialContext is used to locate the backend ConnectionPoolDataSource.
        Parameters:
        key - the JNDI environment property to set.
        value - the value assigned to specified JNDI environment property.
      • getLoginTimeout

        public int getLoginTimeout()
        Get the value of loginTimeout.
        Specified by:
        getLoginTimeout in interface javax.sql.CommonDataSource
        Specified by:
        getLoginTimeout in interface javax.sql.DataSource
        Returns:
        value of loginTimeout.
      • setLoginTimeout

        public void setLoginTimeout​(int v)
        Set the value of loginTimeout.
        Specified by:
        setLoginTimeout in interface javax.sql.CommonDataSource
        Specified by:
        setLoginTimeout in interface javax.sql.DataSource
        Parameters:
        v - Value to assign to loginTimeout.
      • getLogWriter

        public java.io.PrintWriter getLogWriter()
        Get the value of logWriter.
        Specified by:
        getLogWriter in interface javax.sql.CommonDataSource
        Specified by:
        getLogWriter in interface javax.sql.DataSource
        Returns:
        value of logWriter.
      • setLogWriter

        public void setLogWriter​(java.io.PrintWriter v)
        Set the value of logWriter.
        Specified by:
        setLogWriter in interface javax.sql.CommonDataSource
        Specified by:
        setLogWriter in interface javax.sql.DataSource
        Parameters:
        v - Value to assign to logWriter.
      • getTestOnBorrow

        public boolean getTestOnBorrow()
        When true, objects will be {*link PoolableObjectFactory#validateObject validated} before being returned by the {*link #borrowObject} method. If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another.
        See Also:
        setTestOnBorrow(boolean)
      • setTestOnBorrow

        public void setTestOnBorrow​(boolean testOnBorrow)
        When true, objects will be {*link PoolableObjectFactory#validateObject validated} before being returned by the {*link #borrowObject} method. If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another. For a true value to have any effect, the validationQuery property must be set to a non-null string.
        See Also:
        getTestOnBorrow()
      • getTestOnReturn

        public boolean getTestOnReturn()
        When true, objects will be {*link PoolableObjectFactory#validateObject validated} before being returned to the pool within the {*link #returnObject}.
        See Also:
        setTestOnReturn(boolean)
      • setTestOnReturn

        public void setTestOnReturn​(boolean testOnReturn)
        When true, objects will be {*link PoolableObjectFactory#validateObject validated} before being returned to the pool within the {*link #returnObject}. For a true value to have any effect, the validationQuery property must be set to a non-null string.
        See Also:
        getTestOnReturn()
      • getTimeBetweenEvictionRunsMillis

        public int getTimeBetweenEvictionRunsMillis()
        Returns the number of milliseconds to sleep between runs of the idle object evictor thread. When non-positive, no idle object evictor thread will be run.
        See Also:
        setTimeBetweenEvictionRunsMillis(int)
      • setTimeBetweenEvictionRunsMillis

        public void setTimeBetweenEvictionRunsMillis​(int timeBetweenEvictionRunsMillis)
        Sets the number of milliseconds to sleep between runs of the idle object evictor thread. When non-positive, no idle object evictor thread will be run.
        See Also:
        getTimeBetweenEvictionRunsMillis()
      • setNumTestsPerEvictionRun

        public void setNumTestsPerEvictionRun​(int numTestsPerEvictionRun)
        Sets the number of objects to examine during each run of the idle object evictor thread (if any).

        When a negative value is supplied, ceil({*link #numIdle})/abs({*link #getNumTestsPerEvictionRun}) tests will be run. I.e., when the value is -n, roughly one nth of the idle objects will be tested per run.

        See Also:
        getNumTestsPerEvictionRun(), setTimeBetweenEvictionRunsMillis(int)
      • setMinEvictableIdleTimeMillis

        public void setMinEvictableIdleTimeMillis​(int minEvictableIdleTimeMillis)
        Sets the minimum amount of time an object may sit idle in the pool before it is eligable for eviction by the idle object evictor (if any). When non-positive, no objects will be evicted from the pool due to idle time alone.
        See Also:
        getMinEvictableIdleTimeMillis(), setTimeBetweenEvictionRunsMillis(int)
      • getTestWhileIdle

        public boolean getTestWhileIdle()
        When true, objects will be {*link PoolableObjectFactory#validateObject validated} by the idle object evictor (if any). If an object fails to validate, it will be dropped from the pool.
        See Also:
        setTestWhileIdle(boolean), setTimeBetweenEvictionRunsMillis(int)
      • setTestWhileIdle

        public void setTestWhileIdle​(boolean testWhileIdle)
        When true, objects will be {*link PoolableObjectFactory#validateObject validated} by the idle object evictor (if any). If an object fails to validate, it will be dropped from the pool. For a true value to have any effect, the validationQuery property must be set to a non-null string.
        See Also:
        getTestWhileIdle(), setTimeBetweenEvictionRunsMillis(int)
      • getValidationQuery

        public java.lang.String getValidationQuery()
        The SQL query that will be used to validate connections from this pool before returning them to the caller. If specified, this query MUST be an SQL SELECT statement that returns at least one row.
      • setValidationQuery

        public void setValidationQuery​(java.lang.String validationQuery)
        The SQL query that will be used to validate connections from this pool before returning them to the caller. If specified, this query MUST be an SQL SELECT statement that returns at least one row. If none of the properties, testOnBorow, testOnReturn, testWhileIdle have been previously set, calling this method sets testOnBorrow to true.
      • isRollbackAfterValidation

        public boolean isRollbackAfterValidation()
        Whether a rollback will be issued after executing the SQL query that will be used to validate connections from this pool before returning them to the caller.
        Returns:
        true if a rollback will be issued after executing the validation query
        Since:
        1.2.2
      • setRollbackAfterValidation

        public void setRollbackAfterValidation​(boolean rollbackAfterValidation)
        Whether a rollback will be issued after executing the SQL query that will be used to validate connections from this pool before returning them to the caller. Default behavior is NOT to issue a rollback. The setting will only have an effect if a validation query is set
        Parameters:
        rollbackAfterValidation - new property value
        Since:
        1.2.2
      • getConnection

        public java.sql.Connection getConnection()
                                          throws java.sql.SQLException
        Attempt to establish a database connection.
        Specified by:
        getConnection in interface javax.sql.DataSource
        Throws:
        java.sql.SQLException
      • getConnection

        public java.sql.Connection getConnection​(java.lang.String username,
                                                 java.lang.String password)
                                          throws java.sql.SQLException
        Attempt to retrieve a database connection using getPooledConnectionAndInfo(String, String) with the provided username and password. The password on the PooledConnectionAndInfo instance returned by getPooledConnectionAndInfo is compared to the password 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 PooledConnectionAndInfo instance retrieved with the old password is destroyed and the getPooledConnectionAndInfo is repeatedly invoked until a PooledConnectionAndInfo instance with the new password is returned.
        Specified by:
        getConnection in interface javax.sql.DataSource
        Throws:
        java.sql.SQLException
      • getPooledConnectionAndInfo

        protected abstract org.apache.commons.dbcp.datasources.PooledConnectionAndInfo getPooledConnectionAndInfo​(java.lang.String username,
                                                                                                                  java.lang.String password)
                                                                                                           throws java.sql.SQLException
        Throws:
        java.sql.SQLException
      • setupDefaults

        protected abstract void setupDefaults​(java.sql.Connection con,
                                              java.lang.String username)
                                       throws java.sql.SQLException
        Throws:
        java.sql.SQLException
      • testCPDS

        protected javax.sql.ConnectionPoolDataSource testCPDS​(java.lang.String username,
                                                              java.lang.String password)
                                                       throws javax.naming.NamingException,
                                                              java.sql.SQLException
        Throws:
        javax.naming.NamingException
        java.sql.SQLException
      • whenExhaustedAction

        protected byte whenExhaustedAction​(int maxActive,
                                           int maxWait)
      • getReference

        public javax.naming.Reference getReference()
                                            throws javax.naming.NamingException
        Retrieves the Reference of this object. Note: InstanceKeyDataSource subclasses should override this method. The implementaion included below is not robust and will be removed at the next major version DBCP release.
        Specified by:
        getReference in interface javax.naming.Referenceable
        Returns:
        The non-null Reference of this object.
        Throws:
        javax.naming.NamingException - If a naming exception was encountered while retrieving the reference.