Expresso 5-6

com.jcorporate.expresso.core.db
Class DBConnectionPool

java.lang.Object
  extended byjava.lang.Thread
      extended bycom.jcorporate.expresso.core.db.DBConnectionPool
All Implemented Interfaces:
Runnable

public class DBConnectionPool
extends Thread

a generic database connection pooling object.

Any object requiring connection to the database can request a connection from the connection pool, which will re-use connections and allocate new connections as required.

A connection pool will automatically drop connections that have been idle for more than a certain number of seconds when the pool reaches it's maximum size & a new connection is required.

It is the responsibility of the object that requests the connection to release it again as soon as possible.

Author:
Michael Nash

Field Summary
protected  LinkedList available
          Linked list of available connections to use from the connection pool
protected  boolean checkZeroUpdate
          Check zero update setting author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001
protected  EscapeHandler escapeHandler
          Class that performs appropriate escaping in the strings being sent to the partuclar database.
protected  Map inUse
          Map of connections that are currently is use.
protected  long lastUsed
          This is a simple tag for when the last time the pool was ever used.
static int LIMITATION_AFTER_ORDER_BY
          Insert the limitation syntax after ORDER BY key words SELECT {COLUMNS}...
static int LIMITATION_AFTER_SELECT
          Insert the limitation syntax after TABLE nomination SELECT {limitation-syntax} {COLUMNS}...
static int LIMITATION_AFTER_TABLE
          Insert the limitation syntax after TABLE nomination SELECT {COLUMNS}...
static int LIMITATION_AFTER_WHERE
          Insert the limitation syntax after WHERE key word SELECT {COLUMNS}...
static int LIMITATION_DISABLED
          Limitation syntax database vendor specific optimisation is disabled

author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001

protected  int limitationPosition
          Rowset Limitation Optimisation Syntax Position.
protected  String limitationSyntax
          Rowset Limitation Optimisation Syntax String.
protected  Object poolLock
          Object that is used as a lock for both available and isUse lists in a single object.
protected  Object timestampLock
          object to lock finding current timestamp
 
Fields inherited from class java.lang.Thread
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY
 
Constructor Summary
DBConnectionPool()
          Default Constructor
 
Method Summary
protected  DBConnection buildNewConnection()
          Creates a new database connection.
 void clean()
          Clean the connection pool - see if any connections have been idle more than the allowed number of seconds .
protected  void cleanAvailable()
          Iterates once through the available connections and cleans them.
protected  DBConnection createNewConnection()
          Creates a new connection to the data source
 void disconnectAll()
          Disconnect all of the current connections.
protected  void dumpDebugInfo()
          Helper function that dumps all the current contents of the inUse connections.
 void executeExclusiveUpdate(String theSQL)
          This allows an exclusive updated to be done to a database.
 boolean getCheckZeroUpdate()
          Gets the check zero update boolean flag for this database connection pool author Peter Pilgrim
 DBConnection getConnection()
          Find an available connection in the default connection pool, if any.
 DBConnection getConnection(String connectionDescrip)
          Get a connection from the pool.
 String getDataContext()
          Return the current database name/config key
static javax.sql.DataSource getDataSource(String dataContext)
          Retrieve a dumb datasource implementation that is compatible with items such as reporting tools, etc.
 String getDBName()
          Return the current database name/config key
 ArrayList getDefaultWildCards()
          Return a list of default wild card characters.
 String getDistinctRowsetKeyword()
          Gets the SQL keyword to remove duplicate records from a database query.
 EscapeHandler getEscapeHandler()
          Get the current character escape handler for this class.
static DBConnectionPool getInstance(String dataContext)
          Version of getInstance that can only get an already initialized connection pool to an alternate database
protected static com.jcorporate.expresso.core.db.config.JDBCConfig getJDBCConfig(String dataContext)
          Return the JDBConfig regardless of initialization by kernel package or DefaultInit servlet
protected  com.jcorporate.expresso.core.db.config.JNDIConfig getJNDIConfig(com.jcorporate.expresso.core.db.config.JDBCConfig curConfig)
          Function that retrieves the JNDI config.
 int getLimitationPosition()
          programmatically gets the limitation optimisation insertion position

author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001

 String getLimitationSyntax()
          Programmatically gets the limitation syntax string

author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001

 int getMaxConnections()
          Useful for querying the potential of the dbconnection pool's status
 ArrayList getPoolList()
          Return the entire pool of connections as a Vector
 ArrayList getWildCardsList()
           
protected  boolean isFull()
          Helper function to determine if the pool is full.
 boolean isInitialized()
          Is this connection pool initialized, or does it require database parameters?
static void reInitialize()
          Close all existing connections & empty the pools
 void release(DBConnection connectionToRelease)
          Release the given connection It is the object requesting the connection's responsibility to call this method to release the connection(s) it requested.
 void setCheckZeroUpdate(boolean newValue)
          Sets the check zero update boolean flag for this database connection pool author Peter Pilgrim
protected  void setDataContext(String newDBName)
          Set the current database name/config key
protected  void setDBName(String newDBName)
          Set the current database name/config key
 void setDistinctRowsetKeyword(String keyword)
          Sets the SQL keyword to remove duplicate records from a database query.
 void setLimitationPosition(int pos)
          programmatically sets the limitation optimisation insertion position
 void setLimitationPosition(String pos)
          programmatically sets the limitation optimisation insertion position as readable string.
 void setLimitationSyntax(String syntax)
          Programmatically gets the limitation syntax string
 void setMaxConnections(int newMax)
          Sets the maximum number of connections for this pool
 void setTestQuery(String newTestQuery)
          Set a small query to be used to "test" a connection before it's handed out
 void setTimeOutInterval(int newInterval)
          Set the number of seconds that a connection must remain idle before it is considered "timed out" and cleared.
 boolean supportsTransactions()
          Does this database connection support commit/rollback?
static boolean supportsTransactions(String connName)
          Does this database connection support commit/rollback?
 
Methods inherited from class java.lang.Thread
activeCount, checkAccess, countStackFrames, currentThread, destroy, dumpStack, enumerate, getContextClassLoader, getName, getPriority, getThreadGroup, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, run, setContextClassLoader, setDaemon, setName, setPriority, sleep, sleep, start, stop, stop, suspend, toString, yield
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

available

protected LinkedList available
Linked list of available connections to use from the connection pool


inUse

protected Map inUse
Map of connections that are currently is use.


poolLock

protected Object poolLock
Object that is used as a lock for both available and isUse lists in a single object.


timestampLock

protected Object timestampLock
object to lock finding current timestamp


LIMITATION_DISABLED

public static final int LIMITATION_DISABLED
Limitation syntax database vendor specific optimisation is disabled

author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001

See Also:
Constant Field Values

LIMITATION_AFTER_TABLE

public static final int LIMITATION_AFTER_TABLE
Insert the limitation syntax after TABLE nomination SELECT {COLUMNS}... FROM {TABLE} {limitation-syntax} [ WHERE {where_clause}... ] [ ORDER BY {order_by_clause}... ]

author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001

See Also:
Constant Field Values

LIMITATION_AFTER_WHERE

public static final int LIMITATION_AFTER_WHERE
Insert the limitation syntax after WHERE key word SELECT {COLUMNS}... FROM {TABLE} [ WHERE {where_clause}... ] AND {limitation-syntax} [ ORDER BY {order_by_clause}... ]

author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001

See Also:
Constant Field Values

LIMITATION_AFTER_ORDER_BY

public static final int LIMITATION_AFTER_ORDER_BY
Insert the limitation syntax after ORDER BY key words SELECT {COLUMNS}... FROM {TABLE} [ WHERE {where_clause}... ] [ ORDER BY {order_by_clause}... ] {limitation-syntax}

author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001

See Also:
Constant Field Values

LIMITATION_AFTER_SELECT

public static final int LIMITATION_AFTER_SELECT
Insert the limitation syntax after TABLE nomination SELECT {limitation-syntax} {COLUMNS}... FROM {TABLE} [ WHERE {where_clause}... ] [ ORDER BY {order_by_clause}... ]

author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001

Since:
Expresso 4.0
See Also:
Constant Field Values

limitationPosition

protected int limitationPosition
Rowset Limitation Optimisation Syntax Position. Specifies a where in the SQL command the limitation string should be inserted.

author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001

See Also:
LIMITATION_DISABLED, LIMITATION_AFTER_TABLE, LIMITATION_AFTER_WHERE, LIMITATION_AFTER_ORDER_BY, DBObject.searchAndRetrieveList(), DBObject.getOffsetRecord(), DBObject.setOffsetRecord( int ), com.jcorporate.expresso.core.dbobj.DBObject#setMaxRecords(int))

limitationSyntax

protected String limitationSyntax
Rowset Limitation Optimisation Syntax String. Specifies a string to add database query to retrieve only a finite number of rows from the ResultSet.

For example for MYSQL the string should be "LIMIT %offset% , %maxrecord%"

For example for ORACLE the string should be "ROWNUM >= %offset% AND ROWNUM <=%endrecord%"

author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001

See Also:
limitationPosition, DBObject.searchAndRetrieveList(), DBObject.setOffsetRecord( int ), DBObject.setMaxRecords( int )

checkZeroUpdate

protected boolean checkZeroUpdate
Check zero update setting author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001


escapeHandler

protected EscapeHandler escapeHandler
Class that performs appropriate escaping in the strings being sent to the partuclar database.


lastUsed

protected long lastUsed
This is a simple tag for when the last time the pool was ever used. If it has elapsed the timeout time specified in the setup table, then we execute a clean before we try to hand out a connection.

Constructor Detail

DBConnectionPool

public DBConnectionPool()
Default Constructor

Method Detail

buildNewConnection

protected DBConnection buildNewConnection()
                                   throws DBException
Creates a new database connection. It just rather blindly does this without regards to database maximums, so it should rarely be used. Normally it is used internally by createNewConnection().

Returns:
DBConnection object
Throws:
DBException - upon error

createNewConnection

protected DBConnection createNewConnection()
                                    throws DBException
Creates a new connection to the data source

Returns:
a newly instantiated and populated DBConnection, or null if maxconnections is exceeded, or null if "available" list has items, so that we should not be creating.
Throws:
DBException - upon error

cleanAvailable

protected void cleanAvailable()
                       throws ConnectionPoolException
Iterates once through the available connections and cleans them.

Throws:
ConnectionPoolException

clean

public void clean()
           throws ConnectionPoolException,
                  DBException
Clean the connection pool - see if any connections have been idle more than the allowed number of seconds . If so, disconnect & de- allocate them

Throws:
DBException - If an error occurs releasing the stale connection
ConnectionPoolException - for other errors relating internally to the connectionpool code.

disconnectAll

public void disconnectAll()
                   throws DBException
Disconnect all of the current connections. Called when we shut down

Throws:
DBException

executeExclusiveUpdate

public void executeExclusiveUpdate(String theSQL)
                            throws DBException
This allows an exclusive updated to be done to a database. (Such as drop table) should ensure that no tables are in use when this update is executed.

Parameters:
theSQL - the SQL code to execute.
Throws:
DBException

getConnection

public DBConnection getConnection()
                           throws ConnectionPoolException,
                                  PoolFullException,
                                  DBException
Find an available connection in the default connection pool, if any.

If none, make a new one if we can.

Does not set the new connection's description

This method will sleep for "interval" number of seconds if no connections are available and the pool is full. It then tries again to find or allocate a connection before failing.

Returns:
DBConnection A database connection ready for use
Throws:
DBException - If there's an error talking with the Database
PoolFullException - if we're unable to allocate a new connection because the pool is full and we still haven't gotten a connection
ConnectionPoolException - for other connection-pool related errors. author Yves Henri AMAIZO (Modification) author Larry Hamel (Modification)

dumpDebugInfo

protected void dumpDebugInfo()
Helper function that dumps all the current contents of the inUse connections.


isFull

protected boolean isFull()
Helper function to determine if the pool is full.

Returns:
true if the connection pool is full

getConnection

public DBConnection getConnection(String connectionDescrip)
                           throws DBException
Get a connection from the pool. If the pool does not have any free connections (and has not reached it's max size), create a new one.

This version of getConnection sets the new connections description as well, avoiding a seperate call to setDescription

Parameters:
connectionDescrip - A description of the use of the database connection
Returns:
DBConnection A database connection ready for use, or null if no more connections can be allocated
Throws:
DBException - If the pool is not initialized or the connection cannot be established

getDBName

public String getDBName()
Return the current database name/config key

Returns:
The db name

getDataContext

public String getDataContext()
Return the current database name/config key

Returns:
The db name

supportsTransactions

public static boolean supportsTransactions(String connName)
                                    throws DBException
Does this database connection support commit/rollback?

Parameters:
connName - the connection name
Returns:
true if the db supports transactions
Throws:
DBException

supportsTransactions

public boolean supportsTransactions()
                             throws DBException
Does this database connection support commit/rollback?

Returns:
true if the db supports transactions
Throws:
DBException

getInstance

public static DBConnectionPool getInstance(String dataContext)
                                    throws DBException
Version of getInstance that can only get an already initialized connection pool to an alternate database

Returns:
DBConnectionPool The instance of a connection pool
Throws:
DBException - If the alternate pool cannot be created, for example if there is no connection by the given name

getDataSource

public static javax.sql.DataSource getDataSource(String dataContext)
                                          throws SQLException
Retrieve a dumb datasource implementation that is compatible with items such as reporting tools, etc.

Note that performance of the resulting DataSource may be very slow since the datasource is a dumb connector, and does NOT consider the connection pool (because Expresso, at this time, has no way to register for a java.sql.Connection to be removed from the pool when the API programmer closes it)

Parameters:
dataContext - the data context to retrieve the data source for.
Returns:
Throws:
SQLException

getPoolList

public ArrayList getPoolList()
                      throws DBException
Return the entire pool of connections as a Vector

Returns:
ArrayList An array list containing the DBConnection objects
Throws:
DBException - If the pool cannot be returned

getWildCardsList

public ArrayList getWildCardsList()

isInitialized

public boolean isInitialized()
Is this connection pool initialized, or does it require database parameters?

Returns:
true if the DBConnectionPool is initialized

release

public void release(DBConnection connectionToRelease)
Release the given connection It is the object requesting the connection's responsibility to call this method to release the connection(s) it requested.

Parameters:
connectionToRelease - The DBConnection to be released back to the pool.

getMaxConnections

public int getMaxConnections()
Useful for querying the potential of the dbconnection pool's status

Returns:
maximum number of connections allowed.

setMaxConnections

public void setMaxConnections(int newMax)
                       throws DBException
Sets the maximum number of connections for this pool

Parameters:
newMax - The new maximum number of connections
Throws:
DBException

setDBName

protected void setDBName(String newDBName)
Set the current database name/config key

Parameters:
newDBName - The new dataContext to set for this connection pool

setDataContext

protected void setDataContext(String newDBName)
Set the current database name/config key

Parameters:
newDBName - The new dataContext to set for this connection pool

setTestQuery

public void setTestQuery(String newTestQuery)
Set a small query to be used to "test" a connection before it's handed out

Parameters:
newTestQuery - The string to execute as a test query

setTimeOutInterval

public void setTimeOutInterval(int newInterval)
                        throws DBException
Set the number of seconds that a connection must remain idle before it is considered "timed out" and cleared. It also sets the maximum time-to-live for the connection to ten times the interval.

although we are setting long values which are , no sync

Parameters:
newInterval - The new interval value in seconds
Throws:
DBException

reInitialize

public static void reInitialize()
                         throws DBException
Close all existing connections & empty the pools

Throws:
DBException

getLimitationPosition

public int getLimitationPosition()
programmatically gets the limitation optimisation insertion position

author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001

Returns:
an integer code for the limitation syntax position
Since:
Expresso 4.0

setLimitationPosition

public void setLimitationPosition(int pos)
                           throws DBException
programmatically sets the limitation optimisation insertion position

Parameters:
pos - the position
Throws:
DBException - author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001
Since:
Expresso 4.0

setLimitationPosition

public void setLimitationPosition(String pos)
programmatically sets the limitation optimisation insertion position as readable string.

Parameters:
pos - the position as a String author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001
Since:
Expresso 4.0

getLimitationSyntax

public String getLimitationSyntax()
Programmatically gets the limitation syntax string

author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001

Returns:
the limitation syntax string
Since:
Expresso 4.0

getEscapeHandler

public EscapeHandler getEscapeHandler()
Get the current character escape handler for this class.

Returns:
The EscapeHandler for this data context
See Also:
EscapeHandler, DefaultEscapeHandler

setLimitationSyntax

public void setLimitationSyntax(String syntax)
Programmatically gets the limitation syntax string

Parameters:
syntax - the new syntax

author Peter Pilgrim, Thu Jun 21 10:30:59 BST 2001

Since:
Expresso 4.0

setDistinctRowsetKeyword

public void setDistinctRowsetKeyword(String keyword)

Sets the SQL keyword to remove duplicate records from a database query. Most databases use the "DISTINCT" keyword (which is the default), other databases use "UNIQUE".

Source: An old tatty copy of "Introduction to SQL"

Parameters:
keyword - the SQL keyword author Peter Pilgrim
Since:
Expresso 4.0
See Also:
getDistinctRowsetKeyword(), DBObject.searchAndRetrieveList(), DBObject.searchAndRetrieveList( String )

getDistinctRowsetKeyword

public String getDistinctRowsetKeyword()
Gets the SQL keyword to remove duplicate records from a database query.

author Peter Pilgrim

Returns:
The distinct keyword
Since:
Expresso 4.0
See Also:
setDistinctRowsetKeyword( String ), DBObject.searchAndRetrieveList(), com.jcorporate.expresso.core.dbobj.DBObject#setFieldDistinct(java.lang.String, boolean))

setCheckZeroUpdate

public void setCheckZeroUpdate(boolean newValue)
Sets the check zero update boolean flag for this database connection pool author Peter Pilgrim

Parameters:
newValue - true if you want to check for zero updates

getCheckZeroUpdate

public boolean getCheckZeroUpdate()
Gets the check zero update boolean flag for this database connection pool author Peter Pilgrim

Returns:
true if Zero updates are checked for
Since:
Expresso 4.0

getJNDIConfig

protected com.jcorporate.expresso.core.db.config.JNDIConfig getJNDIConfig(com.jcorporate.expresso.core.db.config.JDBCConfig curConfig)
                                                                   throws ConnectionPoolException
Function that retrieves the JNDI config. If this pool is being configured by ConfigManager, then we get the old ConfigJNDI version. If we are using the new kernel package for configuration, then

Parameters:
curConfig - The current config that we hold.
Returns:
a JNDI Configuration object. May be null if none is configured in the system.
Throws:
ConnectionPoolException - upon error getting configuration

getJDBCConfig

protected static com.jcorporate.expresso.core.db.config.JDBCConfig getJDBCConfig(String dataContext)
                                                                          throws ConnectionPoolException
Return the JDBConfig regardless of initialization by kernel package or DefaultInit servlet

Parameters:
dataContext - The name of the data context to retrieve
Returns:
The filled out JDBCConfig object.
Throws:
ConnectionPoolException - upon error getting configuration

getDefaultWildCards

public ArrayList getDefaultWildCards()
Return a list of default wild card characters. This can be used to determine if the search criteria supplied by a user has wild-card characters in it or is an exact match.

Returns:
A list of the wild-card characters

Expresso 5-6

Please see www.jcorporate.com for information about new Expresso releases.