de.esprit.appsuite.database.dbase

## Class DBConnectionPool

- java.lang.Object
- - de.esprit.appsuite.database.dbase.DBConnectionPool

- All Implemented Interfaces:
    Connectable, DBConnectionEvent.Source, CloseableComponent, java.lang.AutoCloseable, java.sql.Wrapper, javax.sql.CommonDataSource, javax.sql.DataSource

      public class DBConnectionPool
      extends java.lang.Object
      implements Connectable, javax.sql.DataSource, CloseableComponent

  This class implements a pool for JDBC database connections. Free connections are stored internally in the free-list whereas used connections are either stored in the used-map or transaction-map depending on whether they run in a transaction or not. These maps store connections based on the current thread (the one who fetched them) as a key.

  Basically a thread owns a connection until he explicitly releases it with the `releaseConnection()` call. Thus If a thread tries to fetch a connection twice he will get exactly the same one he has fetched before. Transacting connections however are NOT released that way but solely by calling `commit()` or `rollback()`.

  Note that you can specify the `min,max` numbers for connections in the pool. The pool ensures, that at least `min` connections are always available. If i.e. a client has closed a connection the pool will recreate one to ensure the `min` value. If more than `min` connections are requested by clients, then the pool is allowed to create new connections up to `max`, which are automatically closed down to `min` again if they aren't needed any more.

  There are three ways to get a connection:

  - wait indefinitely `getConnection()`
    Waits unlimited until a connection becomes available.
  - wait for some time `getConnection(int)`
    Wait for a specified amount of time only. Throws a `ConnectionNotAvailableException` if no connection has become available within that time.
  - no wait `getConnectionNoWait()`
    Returns a connection if one is immediately available, throws a `ConnectionNotAvailableException` otherwise.
  Note that the pool needs to be closed with the `close()` call if no more needed. This cleanly closes all database connections. Any `getConnection()` requests during shutdown will result in an according ShuttingDownException being thrown.
  Author:
    Rainer Buesch

- - ### Constructor Summary

    Constructors
    Constructor and Description
    `DBConnectionPool()` Creates an empty DBConnectionPool which is not connected yet to the database.
    `DBConnectionPool(Credential cred)` Main constructor for the DBConnectionPool
    `DBConnectionPool(java.lang.String jdbcDriver, java.lang.String jdbcURL, java.lang.String jdbcUser, java.lang.String jdbcPassword)`
    `DBConnectionPool(java.lang.String jdbcDriver, java.lang.String jdbcURL, java.lang.String jdbcUser, java.lang.String jdbcPassword, int minConns, int maxConns)`
    `DBConnectionPool(java.lang.String jdbcDriver, java.lang.String jdbcURL, java.lang.String jdbcUser, java.lang.String jdbcPassword, java.lang.String dbSchema)`
    `DBConnectionPool(java.lang.String jdbcDriver, java.lang.String jdbcURL, java.lang.String jdbcUser, java.lang.String jdbcPassword, java.lang.String dbSchema, int minConns, int maxConns)` Main constructor for the DBConnectionPool

  - ### Method Summary

    Methods
    Modifier and Type | Method and Description
    --- | ---
    `void` | `addConnectionListener(DBConnectionEvent.Listener l)` Listeners are notified about a connect and a disconnect
    `int` | `begin()` Acquires a transacting connection for the current thread.
    `int` | `begin(int txIsolationLevel)` Same as begin() but sets the isolation level to TRANSACTION_REPEATABLE_READ.
    `void` | `close()` This method tells the connection pool to shutdown immediately.
    `void` | `close(int shutdownDelay)` This method implements the "shutting down" process.
    `int` | `commit()` Releases the transacting connection of the current thread.
    `void` | `connect(Credential cred)` Connects to the database with the given credential information
    `void` | `disconnect()` Same as close()
    `void` | `dumpPoolParams(java.io.OutputStream os)` Prints the runtime parameters of this connection pool into the given stream.
    `void` | `dumpPoolStatus(java.io.PrintStream ps)` Prints the use-time of each connection in the pool.
    `void` | `dumpUsageSummary(java.io.PrintStream ps)` Prints the use-time of each connection in the pool.
    `DBPoolConnection` | `getConnection()` Returns the next available connection.
    `DBPoolConnection` | `getConnection(int timeout)` This method returns the next available connection.
    `java.sql.Connection` | `getConnection(java.lang.String username, java.lang.String password)` Delegates directly to getConnection().
    `int` | `getConnectionCount()` Returns the total number of connections in the pool (free plus used plus transacting connections).
    `DBPoolConnection` | `getConnectionNoWait()` Immediately returns the next available connection.
    `Credential` | `getCredential()`
    `DBSupport` | `getDBSupport()` Returns the `DBSupport` which provides generic database access routines.
    `java.lang.String` | `getDriverName()`
    `DumpString` | `getDumpString(DumpString s)` Fills the given DumpString with the runtime parameters of this connection pool.
    `int` | `getFreeCount()` Returns the number of free connections.
    `java.lang.String` | `getJdbcDriver()`
    `java.lang.String` | `getJdbcPassword()`
    `java.lang.String` | `getJdbcURL()`
    `java.lang.String` | `getJdbcUser()`
    `int` | `getLoginTimeout()` Returns the login timeout in seconds
    `java.io.PrintWriter` | `getLogWriter()`
    `int` | `getMaxConns()`
    `int` | `getMinConns()`
    `java.util.logging.Logger` | `getParentLogger()`
    `RdbmsInfo` | `getRdbmsInfo()` Returns the the `RdbmsInfo` object describing the database.
    `RdbmsSupport` | `getRdbmsSupport()` Returns the the `RdbmsSupport` which encapsulates rdbms specific features.
    `java.lang.String` | `getStatusString()` Returns the status of connections as a string.
    `int` | `getTransactingCount()` Returns the number of connections in transaction.
    `DBConnectionMap` | `getTransactionMap()`
    `int` | `getUsedCount()` Returns the number of connections in use.
    `DBConnectionMap` | `getUsedMap()`
    `protected DBPoolConnection` | `initConnection(DBPoolConnection newConn)` Is called for each connection that has been newly created.
    `boolean` | `isAlive()` Returns true as long as the connection pool has not yet been closed.
    `boolean` | `isBusy()` Returns true as long as the connection pool has not yet been closed.
    `boolean` | `isConnected()` Returns true as long as the connection pool has connections.
    `static boolean` | `isDebug()` Tells whether the DEBUG flag is set in the pool.
    `boolean` | `isTransacting()` Returns true if the current thread is running a transaction.
    `boolean` | `isWrapperFor(java.lang.Class<?> iface)`
    `void` | `releaseConnection()` Returns the connection of the current thread to the pool.
    `void` | `removeConnectionListener(DBConnectionEvent.Listener l)`
    `boolean` | `rollback()` Releases the transacting connection of the current thread.
    `static void` | `setDebug(boolean state)` Sets the DEBUG flag.
    `void` | `setLoginTimeout(int seconds)`
    `void` | `setLogWriter(java.io.PrintWriter out)`
    `<T> T` | `unwrap(java.lang.Class<T> iface)`

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- - ### Constructor Detail

    - #### DBConnectionPool

          public DBConnectionPool()

      Creates an empty DBConnectionPool which is not connected yet to the database. Use `connect(Credential)` in order to create the connection. Note that you may register as a ConnectionEvent.Listener if you want to be notified about connection state changes.

    - #### DBConnectionPool

          public DBConnectionPool(Credential cred)
                           throws java.lang.Exception

      Main constructor for the DBConnectionPool
      Parameters:
        `cred` - a Credential object with the connection parameters
      Throws:
        `java.lang.Exception` - Thrown if the connection to the database failed

    - #### DBConnectionPool

          public DBConnectionPool(java.lang.String jdbcDriver,
                          java.lang.String jdbcURL,
                          java.lang.String jdbcUser,
                          java.lang.String jdbcPassword)
                           throws java.lang.Exception

      Throws:
        `java.lang.Exception`
      See Also:
        `DBConnectionPool(String jdbcDriver, String jdbcURL, String jdbcUser, String jdbcPassword, String dbSchema, int minConns, int maxConns)`

    - #### DBConnectionPool

          public DBConnectionPool(java.lang.String jdbcDriver,
                          java.lang.String jdbcURL,
                          java.lang.String jdbcUser,
                          java.lang.String jdbcPassword,
                          java.lang.String dbSchema)
                           throws java.lang.Exception

      Throws:
        `java.lang.Exception`
      See Also:
        `DBConnectionPool(String jdbcDriver, String jdbcURL, String jdbcUser, String jdbcPassword, String dbSchema, int minConns, int maxConns)`

    - #### DBConnectionPool

          public DBConnectionPool(java.lang.String jdbcDriver,
                          java.lang.String jdbcURL,
                          java.lang.String jdbcUser,
                          java.lang.String jdbcPassword,
                          int minConns,
                          int maxConns)
                           throws java.lang.Exception

      Throws:
        `java.lang.Exception`
      See Also:
        `DBConnectionPool(String jdbcDriver, String jdbcURL, String jdbcUser, String jdbcPassword, String dbSchema, int minConns, int maxConns)`

    - #### DBConnectionPool

          public DBConnectionPool(java.lang.String jdbcDriver,
                          java.lang.String jdbcURL,
                          java.lang.String jdbcUser,
                          java.lang.String jdbcPassword,
                          java.lang.String dbSchema,
                          int minConns,
                          int maxConns)
                           throws java.lang.Exception

      Main constructor for the DBConnectionPool
      Parameters:
        `jdbcDriver` - The JDBC fully-qualified Driver class name
        `jdbcURL` - The JDBC connection URL
        `jdbcUser` - Database login name
        `jdbcPassword` - Database password
        `dbSchema` - Database schema
        `minConns` - Minimum number of pool connections to start with
        `maxConns` - Maximum number of connections that the pool can grow up to
      Throws:
        `java.lang.Exception` - Thrown if the connection to the database failed

  - ### Method Detail

    - #### getUsedMap

          public DBConnectionMap getUsedMap()

    - #### getTransactionMap

          public DBConnectionMap getTransactionMap()

    - #### connect

          public void connect(Credential cred)
                       throws java.lang.Exception

      Connects to the database with the given credential information
      Specified by:
        `connect` in interface `Connectable`
      Throws:
        `java.lang.Exception`

    - #### getRdbmsSupport

          public RdbmsSupport getRdbmsSupport()

      Returns the the `RdbmsSupport` which encapsulates rdbms specific features.

    - #### getRdbmsInfo

          public RdbmsInfo getRdbmsInfo()

      Returns the the `RdbmsInfo` object describing the database.

    - #### addConnectionListener

          public void addConnectionListener(DBConnectionEvent.Listener l)

      Listeners are notified about a connect and a disconnect
      Specified by:
        `addConnectionListener` in interface `DBConnectionEvent.Source`

    - #### removeConnectionListener

          public void removeConnectionListener(DBConnectionEvent.Listener l)

      Specified by:
        `removeConnectionListener` in interface `DBConnectionEvent.Source`

    - #### getDBSupport

          public DBSupport getDBSupport()

      Returns the `DBSupport` which provides generic database access routines.

    - #### getCredential

          public Credential getCredential()

      Returns:
        The the Credential which was used to create the database connection.

    - #### getJdbcDriver

          public java.lang.String getJdbcDriver()

      Returns:
        The JDBC Driver for this connection pool.

    - #### getJdbcURL

          public java.lang.String getJdbcURL()

      Returns:
        The JDBC URL for this connection pool.

    - #### getJdbcUser

          public java.lang.String getJdbcUser()

      Returns:
        The JDBC user-name for this connection pool.

    - #### getJdbcPassword

          public java.lang.String getJdbcPassword()

      Returns:
        The JDBC password for this connection pool.

    - #### getMinConns

          public int getMinConns()

      Returns:
        The minimum number of connections for this pool.

    - #### getMaxConns

          public int getMaxConns()

      Returns:
        The maximum number of connections for this pool.

    - #### getDriverName

          public java.lang.String getDriverName()

      Returns:
        The name of the JDBC Driver class.

    - #### getConnectionNoWait

          public DBPoolConnection getConnectionNoWait()
                                               throws ConnectionNotAvailableException,
                                                      ShuttingDownException

      Immediately returns the next available connection. Throws a ConnNotAvailableException if a connection is not immediately available.
      Returns:
        Connection The next available JDBC connection
      Throws:
        `ConnectionNotAvailableException` - Thrown if no connection is available immediately
        `ShuttingDownException` - Thrown if the connection pool is shutting down

    - #### getConnection

          public DBPoolConnection getConnection()
                                         throws ShuttingDownException

      Returns the next available connection. It will wait indefinitely for a free connection, unless the pool is shutting down.
      Specified by:
        `getConnection` in interface `javax.sql.DataSource`
      Returns:
        the next available JDBC connection
      Throws:
        `ShuttingDownException` - Thrown if the connection pool is shutting down.

    - #### getConnection

          public DBPoolConnection getConnection(int timeout)
                                         throws ShuttingDownException,
                                                ConnectionNotAvailableException

      This method returns the next available connection. It will wait the specified amount of time to get one.
      Returns:
        Connection The next available JDBC connection
      Throws:
        `ConnectionNotAvailableException` - Thrown if no connection is available
        `ShuttingDownException` - Thrown if the connection pool is shutting down

    - #### releaseConnection

          public void releaseConnection()
                                 throws ConnNeverTakenException

      Returns the connection of the current thread to the pool. If the connection is transacting it will be committed or rolled back respectively - depending on whether it was returned by the `commit()` or `rollback()` call.
      Throws:
        `ConnNeverTakenException`
      See Also:
        `Commits and releases a transacting connection`, `Rolls back and releases a transacting connection`

    - #### disconnect

          public void disconnect()

      Same as close()
      Specified by:
        `disconnect` in interface `Connectable`

    - #### close

          public void close()

      This method tells the connection pool to shutdown immediately. Any running transaction will be killed and rolled back.
      Specified by:
        `close` in interface `java.lang.AutoCloseable`

    - #### close

          public void close(int shutdownDelay)

      This method implements the "shutting down" process. It's job is to close all connections in the pool. Note that the DBConnectionPool will reject requests during shutdown by throwing a SuttingDownException.

      If there are still connections in use this process will allow any running transactions a shutdownDelay "courtesy timeout" in order to give them a chance to complete.

      Parameters:
        `shutdownDelay` - millis before shutting down, '-1' = immediate (kill all user threads) , '0' = wait unlimited until all users are gone, '>0' = wait specified amount of millis for users to complete their work.

    - #### getConnectionCount

          public int getConnectionCount()

      Returns the total number of connections in the pool (free plus used plus transacting connections). Note that the count may vary if the `minConns` and `maxConns` parameters differ.

    - #### isAlive

          public boolean isAlive()

      Returns true as long as the connection pool has not yet been closed. During shutdown all requests for getting a connection will result in a ShuttingDownException being thrown.

    - #### isBusy

          public boolean isBusy()

      Returns true as long as the connection pool has not yet been closed. During shutdown all requests for getting a connection will result in a ShuttingDownException being thrown.

    - #### isConnected

          public boolean isConnected()

      Returns true as long as the connection pool has connections.
      Specified by:
        `isConnected` in interface `Connectable`

    - #### isTransacting

          public boolean isTransacting()

      Returns true if the current thread is running a transaction.

    - #### getTransactingCount

          public int getTransactingCount()

      Returns the number of connections in transaction.

    - #### getUsedCount

          public int getUsedCount()

      Returns the number of connections in use.

    - #### getFreeCount

          public int getFreeCount()

      Returns the number of free connections.

    - #### getStatusString

          public java.lang.String getStatusString()

      Returns the status of connections as a string.

    - #### dumpPoolStatus

          public void dumpPoolStatus(java.io.PrintStream ps)

      Prints the use-time of each connection in the pool.

    - #### dumpUsageSummary

          public void dumpUsageSummary(java.io.PrintStream ps)

      Prints the use-time of each connection in the pool.

    - #### dumpPoolParams

          public void dumpPoolParams(java.io.OutputStream os)

      Prints the runtime parameters of this connection pool into the given stream.

    - #### getDumpString

          public DumpString getDumpString(DumpString s)

      Fills the given DumpString with the runtime parameters of this connection pool.

    - #### begin

          public int begin()
                    throws java.sql.SQLException

      Acquires a transacting connection for the current thread. A transaction is started on the connection and it is put into the internal transaction pool. If the same thread requests a connection again it will always get exactly the same one until he either calls commit() or rollback().

      Note that nested transactions are supported. Thus begin() may be called n times by the same thread, each call increasing the nesting level. Accordingly commit() must be called n times decreasing the nesting level again. If nesting level 0 is reached by a commit() call then the database COMMIT is actually performed. A rollback() call at any nesting level will immediately break the transaction and fall back to nesting level 0.

      Returns:
        the current transaction nesting level
      Throws:
        `java.sql.SQLException`

    - #### begin

          public int begin(int txIsolationLevel)
                    throws java.sql.SQLException

      Same as begin() but sets the isolation level to TRANSACTION_REPEATABLE_READ.
      Throws:
        `java.sql.SQLException`

    - #### commit

          public int commit()
                     throws java.sql.SQLException,
                            NotInTransactionException

      Releases the transacting connection of the current thread. The transaction is committed and the connection is put back into the free pool.
      Returns:
        the current transaction nesting level
      Throws:
        `java.sql.SQLException`
        `NotInTransactionException`

    - #### rollback

          public boolean rollback()

      Releases the transacting connection of the current thread. The transaction is rolled back and the connection is put back into the free pool.

      Note that this method does intentionally NOT throw an Exception. If the rollback fails in the database then there is nothing we can do about it anyway.

    - #### setDebug

          public static void setDebug(boolean state)

      Sets the DEBUG flag. If this flag is set all pool actions are reported to the error console.

    - #### isDebug

          public static boolean isDebug()

      Tells whether the DEBUG flag is set in the pool. If this flag is set all pool actions are reported to the error console.

    - #### initConnection

          protected DBPoolConnection initConnection(DBPoolConnection newConn)
                                             throws java.lang.Exception

      Is called for each connection that has been newly created. The default implementation is empty, maybe overridden to perform a customer specific initialization.
      Returns:
        the initialized connection as a convenience return
      Throws:
        `java.lang.Exception`

    - #### getConnection

          public java.sql.Connection getConnection(java.lang.String username,
                                          java.lang.String password)
                                            throws java.sql.SQLException

      Delegates directly to getConnection(). Username and password are just ignored.
      Specified by:
        `getConnection` in interface `javax.sql.DataSource`
      Throws:
        `java.sql.SQLException`

    - #### getLoginTimeout

          public int getLoginTimeout()

      Returns the login timeout in seconds
      Specified by:
        `getLoginTimeout` in interface `javax.sql.CommonDataSource`

    - #### getLogWriter

          public java.io.PrintWriter getLogWriter()

      Specified by:
        `getLogWriter` in interface `javax.sql.CommonDataSource`

    - #### setLoginTimeout

          public void setLoginTimeout(int seconds)

      Specified by:
        `setLoginTimeout` in interface `javax.sql.CommonDataSource`

    - #### setLogWriter

          public void setLogWriter(java.io.PrintWriter out)

      Specified by:
        `setLogWriter` in interface `javax.sql.CommonDataSource`

    - #### 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`

    - #### getParentLogger

          public java.util.logging.Logger getParentLogger()
                                                   throws java.sql.SQLFeatureNotSupportedException

      Specified by:
        `getParentLogger` in interface `javax.sql.CommonDataSource`
      Throws:
        `java.sql.SQLFeatureNotSupportedException`

Copyright © 2014 EsprIT-Systems. All Rights Reserved.