This commit is contained in:
2024-11-30 19:03:49 +08:00
commit 1e6763c160
3806 changed files with 737676 additions and 0 deletions

View File

@@ -0,0 +1,308 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.dbcp.dbcp2.cpdsadapter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.tomcat.dbcp.dbcp2.DelegatingCallableStatement;
import org.apache.tomcat.dbcp.dbcp2.DelegatingConnection;
import org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement;
/**
* This class is the <code>Connection</code> that will be returned from
* <code>PooledConnectionImpl.getConnection()</code>. Most methods are wrappers around the JDBC 1.x
* <code>Connection</code>. A few exceptions include preparedStatement and close. In accordance with the JDBC
* specification this Connection cannot be used after closed() is called. Any further usage will result in an
* SQLException.
* <p>
* ConnectionImpl extends DelegatingConnection to enable access to the underlying connection.
* </p>
*
* @since 2.0
*/
class ConnectionImpl extends DelegatingConnection<Connection> {
private final boolean accessToUnderlyingConnectionAllowed;
/** The object that instantiated this object */
private final PooledConnectionImpl pooledConnection;
/**
* Creates a <code>ConnectionImpl</code>.
*
* @param pooledConnection
* The PooledConnection that is calling the ctor.
* @param connection
* The JDBC 1.x Connection to wrap.
* @param accessToUnderlyingConnectionAllowed
* if true, then access is allowed to the underlying connection
*/
ConnectionImpl(final PooledConnectionImpl pooledConnection, final Connection connection,
final boolean accessToUnderlyingConnectionAllowed) {
super(connection);
this.pooledConnection = pooledConnection;
this.accessToUnderlyingConnectionAllowed = accessToUnderlyingConnectionAllowed;
}
/**
* Marks the Connection as closed, and notifies the pool that the pooled connection is available.
* <p>
* In accordance with the JDBC specification this Connection cannot be used after closed() is called. Any further
* usage will result in an SQLException.
* </p>
*
* @throws SQLException
* The database connection couldn't be closed.
*/
@Override
public void close() throws SQLException {
if (!isClosedInternal()) {
try {
passivate();
} finally {
setClosedInternal(true);
pooledConnection.notifyListeners();
}
}
}
/**
* If pooling of <code>CallableStatement</code>s is turned on in the {@link DriverAdapterCPDS}, a pooled object may
* be returned, otherwise delegate to the wrapped JDBC 1.x {@link java.sql.Connection}.
*
* @param sql
* an SQL statement that may contain one or more '?' parameter placeholders. Typically this statement is
* specified using JDBC call escape syntax.
* @return a default <code>CallableStatement</code> object containing the pre-compiled SQL statement.
* @exception SQLException
* Thrown if a database access error occurs or this method is called on a closed connection.
* @since 2.4.0
*/
@Override
public CallableStatement prepareCall(final String sql) throws SQLException {
checkOpen();
try {
return new DelegatingCallableStatement(this, pooledConnection.prepareCall(sql));
} catch (final SQLException e) {
handleException(e); // Does not return
return null;
}
}
/**
* If pooling of <code>CallableStatement</code>s is turned on in the {@link DriverAdapterCPDS}, a pooled object may
* be returned, otherwise delegate to the wrapped JDBC 1.x {@link java.sql.Connection}.
*
* @param sql
* a <code>String</code> object that is the SQL statement to be sent to the database; may contain on or
* more '?' parameters.
* @param resultSetType
* a result set type; one of <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>.
* @param resultSetConcurrency
* a concurrency type; one of <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>.
* @return a <code>CallableStatement</code> object containing the pre-compiled SQL statement that will produce
* <code>ResultSet</code> objects with the given type and concurrency.
* @throws SQLException
* Thrown if a database access error occurs, this method is called on a closed connection or the given
* parameters are not <code>ResultSet</code> constants indicating type and concurrency.
* @since 2.4.0
*/
@Override
public CallableStatement prepareCall(final String sql, final int resultSetType, final int resultSetConcurrency)
throws SQLException {
checkOpen();
try {
return new DelegatingCallableStatement(this,
pooledConnection.prepareCall(sql, resultSetType, resultSetConcurrency));
} catch (final SQLException e) {
handleException(e); // Does not return
return null;
}
}
/**
* If pooling of <code>CallableStatement</code>s is turned on in the {@link DriverAdapterCPDS}, a pooled object may
* be returned, otherwise delegate to the wrapped JDBC 1.x {@link java.sql.Connection}.
*
* @param sql
* a <code>String</code> object that is the SQL statement to be sent to the database; may contain on or
* more '?' parameters.
* @param resultSetType
* one of the following <code>ResultSet</code> constants: <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>.
* @param resultSetConcurrency
* one of the following <code>ResultSet</code> constants: <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>.
* @param resultSetHoldability
* one of the following <code>ResultSet</code> constants: <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code>
* or <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>.
* @return a new <code>CallableStatement</code> object, containing the pre-compiled SQL statement, that will
* generate <code>ResultSet</code> objects with the given type, concurrency, and holdability.
* @throws SQLException
* Thrown if a database access error occurs, this method is called on a closed connection or the given
* parameters are not <code>ResultSet</code> constants indicating type, concurrency, and holdability.
* @since 2.4.0
*/
@Override
public CallableStatement prepareCall(final String sql, final int resultSetType, final int resultSetConcurrency,
final int resultSetHoldability) throws SQLException {
checkOpen();
try {
return new DelegatingCallableStatement(this,
pooledConnection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability));
} catch (final SQLException e) {
handleException(e); // Does not return
return null;
}
}
/**
* If pooling of <code>PreparedStatement</code>s is turned on in the {@link DriverAdapterCPDS}, a pooled object may
* be returned, otherwise delegate to the wrapped JDBC 1.x {@link java.sql.Connection}.
*
* @param sql
* SQL statement to be prepared
* @return the prepared statement
* @throws SQLException
* if this connection is closed or an error occurs in the wrapped connection.
*/
@Override
public PreparedStatement prepareStatement(final String sql) throws SQLException {
checkOpen();
try {
return new DelegatingPreparedStatement(this, pooledConnection.prepareStatement(sql));
} catch (final SQLException e) {
handleException(e); // Does not return
return null;
}
}
/**
* If pooling of <code>PreparedStatement</code>s is turned on in the {@link DriverAdapterCPDS}, a pooled object may
* be returned, otherwise delegate to the wrapped JDBC 1.x {@link java.sql.Connection}.
*
* @throws SQLException
* if this connection is closed or an error occurs in the wrapped connection.
*/
@Override
public PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency)
throws SQLException {
checkOpen();
try {
return new DelegatingPreparedStatement(this,
pooledConnection.prepareStatement(sql, resultSetType, resultSetConcurrency));
} catch (final SQLException e) {
handleException(e);
return null;
}
}
@Override
public PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency,
final int resultSetHoldability) throws SQLException {
checkOpen();
try {
return new DelegatingPreparedStatement(this,
pooledConnection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability));
} catch (final SQLException e) {
handleException(e);
return null;
}
}
@Override
public PreparedStatement prepareStatement(final String sql, final int autoGeneratedKeys) throws SQLException {
checkOpen();
try {
return new DelegatingPreparedStatement(this, pooledConnection.prepareStatement(sql, autoGeneratedKeys));
} catch (final SQLException e) {
handleException(e);
return null;
}
}
@Override
public PreparedStatement prepareStatement(final String sql, final int columnIndexes[]) throws SQLException {
checkOpen();
try {
return new DelegatingPreparedStatement(this, pooledConnection.prepareStatement(sql, columnIndexes));
} catch (final SQLException e) {
handleException(e);
return null;
}
}
@Override
public PreparedStatement prepareStatement(final String sql, final String columnNames[]) throws SQLException {
checkOpen();
try {
return new DelegatingPreparedStatement(this, pooledConnection.prepareStatement(sql, columnNames));
} catch (final SQLException e) {
handleException(e);
return null;
}
}
//
// Methods for accessing the delegate connection
//
/**
* If false, getDelegate() and getInnermostDelegate() will return null.
*
* @return true if access is allowed to the underlying connection
* @see ConnectionImpl
*/
public boolean isAccessToUnderlyingConnectionAllowed() {
return accessToUnderlyingConnectionAllowed;
}
/**
* Get the delegated connection, if allowed.
*
* @return the internal connection, or null if access is not allowed.
* @see #isAccessToUnderlyingConnectionAllowed()
*/
@Override
public Connection getDelegate() {
if (isAccessToUnderlyingConnectionAllowed()) {
return getDelegateInternal();
}
return null;
}
/**
* Get the innermost connection, if allowed.
*
* @return the innermost internal connection, or null if access is not allowed.
* @see #isAccessToUnderlyingConnectionAllowed()
*/
@Override
public Connection getInnermostDelegate() {
if (isAccessToUnderlyingConnectionAllowed()) {
return super.getInnermostDelegateInternal();
}
return null;
}
}

View File

@@ -0,0 +1,779 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.dbcp.dbcp2.cpdsadapter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Hashtable;
import java.util.Properties;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.Referenceable;
import javax.naming.StringRefAddr;
import javax.naming.spi.ObjectFactory;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;
import org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement;
import org.apache.tomcat.dbcp.dbcp2.PStmtKey;
import org.apache.tomcat.dbcp.dbcp2.Utils;
import org.apache.tomcat.dbcp.pool2.KeyedObjectPool;
import org.apache.tomcat.dbcp.pool2.impl.BaseObjectPoolConfig;
import org.apache.tomcat.dbcp.pool2.impl.GenericKeyedObjectPool;
import org.apache.tomcat.dbcp.pool2.impl.GenericKeyedObjectPoolConfig;
/**
* <p>
* An adapter for JDBC drivers that do not include an implementation of {@link javax.sql.ConnectionPoolDataSource}, but
* still include a {@link java.sql.DriverManager} implementation. <code>ConnectionPoolDataSource</code>s are not used
* within general applications. They are used by <code>DataSource</code> implementations that pool
* <code>Connection</code>s, such as {@link org.apache.tomcat.dbcp.dbcp2.datasources.SharedPoolDataSource}. A J2EE container
* will normally provide some method of initializing the <code>ConnectionPoolDataSource</code> whose attributes are
* presented as bean getters/setters and then deploying it via JNDI. It is then available as a source of physical
* connections to the database, when the pooling <code>DataSource</code> needs to create a new physical connection.
* </p>
* <p>
* Although normally used within a JNDI environment, the DriverAdapterCPDS can be instantiated and initialized as any
* bean and then attached directly to a pooling <code>DataSource</code>. <code>Jdbc2PoolDataSource</code> can use the
* <code>ConnectionPoolDataSource</code> with or without the use of JNDI.
* </p>
* <p>
* The DriverAdapterCPDS also provides <code>PreparedStatement</code> pooling which is not generally available in jdbc2
* <code>ConnectionPoolDataSource</code> implementation, but is addressed within the jdbc3 specification. The
* <code>PreparedStatement</code> pool in DriverAdapterCPDS has been in the dbcp package for some time, but it has not
* undergone extensive testing in the configuration used here. It should be considered experimental and can be toggled
* with the poolPreparedStatements attribute.
* </p>
* <p>
* The <a href="package-summary.html">package documentation</a> contains an example using catalina and JNDI. The
* <a href="../datasources/package-summary.html">datasources package documentation</a> shows how to use
* <code>DriverAdapterCPDS</code> as a source for <code>Jdbc2PoolDataSource</code> without the use of JNDI.
* </p>
*
* @since 2.0
*/
public class DriverAdapterCPDS implements ConnectionPoolDataSource, Referenceable, Serializable, ObjectFactory {
private static final String KEY_USER = "user";
private static final String KEY_PASSWORD = "password";
private static final long serialVersionUID = -4820523787212147844L;
private static final String GET_CONNECTION_CALLED = "A PooledConnection was already requested from this source, "
+ "further initialization is not allowed.";
static {
// Attempt to prevent deadlocks - see DBCP - 272
DriverManager.getDrivers();
}
/** Description */
private String description;
/** Url name */
private String url;
/** User name */
private String userName;
/** User password */
private char[] userPassword;
/** Driver class name */
private String driver;
/** Login TimeOut in seconds */
private int loginTimeout;
/** Log stream. NOT USED */
private transient PrintWriter logWriter;
// PreparedStatement pool properties
private boolean poolPreparedStatements;
private int maxIdle = 10;
private long timeBetweenEvictionRunsMillis = BaseObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
private int numTestsPerEvictionRun = -1;
private int minEvictableIdleTimeMillis = -1;
private int maxPreparedStatements = -1;
/** Whether or not getConnection has been called */
private volatile boolean getConnectionCalled;
/** Connection properties passed to JDBC Driver */
private Properties connectionProperties;
/**
* Controls access to the underlying connection
*/
private boolean accessToUnderlyingConnectionAllowed;
/**
* Default no-arg constructor for Serialization
*/
public DriverAdapterCPDS() {
}
/**
* Throws an IllegalStateException, if a PooledConnection has already been requested.
*/
private void assertInitializationAllowed() throws IllegalStateException {
if (getConnectionCalled) {
throw new IllegalStateException(GET_CONNECTION_CALLED);
}
}
private boolean getBooleanContentString(RefAddr ra) {
return Boolean.valueOf(getStringContent(ra)).booleanValue();
}
/**
* Gets the connection properties passed to the JDBC driver.
*
* @return the JDBC connection properties used when creating connections.
*/
public Properties getConnectionProperties() {
return connectionProperties;
}
/**
* Gets the value of description. This property is here for use by the code which will deploy this datasource. It is
* not used internally.
*
* @return value of description, may be null.
* @see #setDescription(String)
*/
public String getDescription() {
return description;
}
/**
* Gets the driver class name.
*
* @return value of driver.
*/
public String getDriver() {
return driver;
}
private int getIntegerStringContent(final RefAddr ra) {
return Integer.parseInt(getStringContent(ra));
}
/**
* Gets the maximum time in seconds that this data source can wait while attempting to connect to a database. NOT
* USED.
*/
@Override
public int getLoginTimeout() {
return loginTimeout;
}
/**
* Gets the log writer for this data source. NOT USED.
*/
@Override
public PrintWriter getLogWriter() {
return logWriter;
}
/**
* Gets the maximum number of statements that can remain idle in the pool, without extra ones being released, or
* negative for no limit.
*
* @return the value of maxIdle
*/
public int getMaxIdle() {
return this.maxIdle;
}
/**
* Gets the maximum number of prepared statements.
*
* @return maxPrepartedStatements value
*/
public int getMaxPreparedStatements() {
return maxPreparedStatements;
}
/**
* Gets the minimum amount of time a statement may sit idle in the pool before it is eligible for eviction by the
* idle object evictor (if any).
*
* @see #setMinEvictableIdleTimeMillis
* @see #setTimeBetweenEvictionRunsMillis
* @return the minimum amount of time a statement may sit idle in the pool.
*/
public int getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
/**
* Gets the number of statements to examine during each run of the idle object evictor thread (if any.)
*
* @see #setNumTestsPerEvictionRun
* @see #setTimeBetweenEvictionRunsMillis
* @return the number of statements to examine during each run of the idle object evictor thread (if any.)
*/
public int getNumTestsPerEvictionRun() {
return numTestsPerEvictionRun;
}
/**
* Implements {@link ObjectFactory} to create an instance of this class
*/
@Override
public Object getObjectInstance(final Object refObj, final Name name, final Context context,
final Hashtable<?, ?> env) throws Exception {
// The spec says to return null if we can't create an instance
// of the reference
DriverAdapterCPDS cpds = null;
if (refObj instanceof Reference) {
final Reference ref = (Reference) refObj;
if (ref.getClassName().equals(getClass().getName())) {
RefAddr ra = ref.get("description");
if (isNotEmpty(ra)) {
setDescription(getStringContent(ra));
}
ra = ref.get("driver");
if (isNotEmpty(ra)) {
setDriver(getStringContent(ra));
}
ra = ref.get("url");
if (isNotEmpty(ra)) {
setUrl(getStringContent(ra));
}
ra = ref.get(KEY_USER);
if (isNotEmpty(ra)) {
setUser(getStringContent(ra));
}
ra = ref.get(KEY_PASSWORD);
if (isNotEmpty(ra)) {
setPassword(getStringContent(ra));
}
ra = ref.get("poolPreparedStatements");
if (isNotEmpty(ra)) {
setPoolPreparedStatements(getBooleanContentString(ra));
}
ra = ref.get("maxIdle");
if (isNotEmpty(ra)) {
setMaxIdle(getIntegerStringContent(ra));
}
ra = ref.get("timeBetweenEvictionRunsMillis");
if (isNotEmpty(ra)) {
setTimeBetweenEvictionRunsMillis(getIntegerStringContent(ra));
}
ra = ref.get("numTestsPerEvictionRun");
if (isNotEmpty(ra)) {
setNumTestsPerEvictionRun(getIntegerStringContent(ra));
}
ra = ref.get("minEvictableIdleTimeMillis");
if (isNotEmpty(ra)) {
setMinEvictableIdleTimeMillis(getIntegerStringContent(ra));
}
ra = ref.get("maxPreparedStatements");
if (isNotEmpty(ra)) {
setMaxPreparedStatements(getIntegerStringContent(ra));
}
ra = ref.get("accessToUnderlyingConnectionAllowed");
if (isNotEmpty(ra)) {
setAccessToUnderlyingConnectionAllowed(getBooleanContentString(ra));
}
cpds = this;
}
}
return cpds;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw new SQLFeatureNotSupportedException();
}
/**
* Gets the value of password for the default user.
*
* @return value of password.
*/
public String getPassword() {
return Utils.toString(userPassword);
}
/**
* Gets the value of password for the default user.
*
* @return value of password.
* @since 2.4.0
*/
public char[] getPasswordCharArray() {
return userPassword;
}
/**
* Attempts to establish a database connection using the default user and password.
*/
@Override
public PooledConnection getPooledConnection() throws SQLException {
return getPooledConnection(getUser(), getPassword());
}
/**
* Attempts to establish a database connection.
*
* @param pooledUserName
* name to be used for the connection
* @param pooledUserPassword
* password to be used fur the connection
*/
@Override
public PooledConnection getPooledConnection(final String pooledUserName, final String pooledUserPassword)
throws SQLException {
getConnectionCalled = true;
PooledConnectionImpl pooledConnection = null;
// Workaround for buggy WebLogic 5.1 classloader - ignore the exception upon first invocation.
try {
if (connectionProperties != null) {
update(connectionProperties, KEY_USER, pooledUserName);
update(connectionProperties, KEY_PASSWORD, pooledUserPassword);
pooledConnection = new PooledConnectionImpl(
DriverManager.getConnection(getUrl(), connectionProperties));
} else {
pooledConnection = new PooledConnectionImpl(
DriverManager.getConnection(getUrl(), pooledUserName, pooledUserPassword));
}
pooledConnection.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
} catch (final ClassCircularityError e) {
if (connectionProperties != null) {
pooledConnection = new PooledConnectionImpl(
DriverManager.getConnection(getUrl(), connectionProperties));
} else {
pooledConnection = new PooledConnectionImpl(
DriverManager.getConnection(getUrl(), pooledUserName, pooledUserPassword));
}
pooledConnection.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
}
KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> stmtPool = null;
if (isPoolPreparedStatements()) {
final GenericKeyedObjectPoolConfig<DelegatingPreparedStatement> config = new GenericKeyedObjectPoolConfig<>();
config.setMaxTotalPerKey(Integer.MAX_VALUE);
config.setBlockWhenExhausted(false);
config.setMaxWaitMillis(0);
config.setMaxIdlePerKey(getMaxIdle());
if (getMaxPreparedStatements() <= 0) {
// since there is no limit, create a prepared statement pool with an eviction thread;
// evictor settings are the same as the connection pool settings.
config.setTimeBetweenEvictionRunsMillis(getTimeBetweenEvictionRunsMillis());
config.setNumTestsPerEvictionRun(getNumTestsPerEvictionRun());
config.setMinEvictableIdleTimeMillis(getMinEvictableIdleTimeMillis());
} else {
// since there is a limit, create a prepared statement pool without an eviction thread;
// pool has LRU functionality so when the limit is reached, 15% of the pool is cleared.
// see org.apache.commons.pool2.impl.GenericKeyedObjectPool.clearOldest method
config.setMaxTotal(getMaxPreparedStatements());
config.setTimeBetweenEvictionRunsMillis(-1);
config.setNumTestsPerEvictionRun(0);
config.setMinEvictableIdleTimeMillis(0);
}
stmtPool = new GenericKeyedObjectPool<>(pooledConnection, config);
pooledConnection.setStatementPool(stmtPool);
}
return pooledConnection;
}
/**
* Implements {@link Referenceable}.
*/
@Override
public Reference getReference() throws NamingException {
// this class implements its own factory
final String factory = getClass().getName();
final Reference ref = new Reference(getClass().getName(), factory, null);
ref.add(new StringRefAddr("description", getDescription()));
ref.add(new StringRefAddr("driver", getDriver()));
ref.add(new StringRefAddr("loginTimeout", String.valueOf(getLoginTimeout())));
ref.add(new StringRefAddr(KEY_PASSWORD, getPassword()));
ref.add(new StringRefAddr(KEY_USER, getUser()));
ref.add(new StringRefAddr("url", getUrl()));
ref.add(new StringRefAddr("poolPreparedStatements", String.valueOf(isPoolPreparedStatements())));
ref.add(new StringRefAddr("maxIdle", String.valueOf(getMaxIdle())));
ref.add(new StringRefAddr("timeBetweenEvictionRunsMillis", String.valueOf(getTimeBetweenEvictionRunsMillis())));
ref.add(new StringRefAddr("numTestsPerEvictionRun", String.valueOf(getNumTestsPerEvictionRun())));
ref.add(new StringRefAddr("minEvictableIdleTimeMillis", String.valueOf(getMinEvictableIdleTimeMillis())));
ref.add(new StringRefAddr("maxPreparedStatements", String.valueOf(getMaxPreparedStatements())));
return ref;
}
private String getStringContent(RefAddr ra) {
return ra.getContent().toString();
}
/**
* Gets 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.
*
* @return the value of the evictor thread timer
* @see #setTimeBetweenEvictionRunsMillis(long)
*/
public long getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
/**
* Gets the value of url used to locate the database for this datasource.
*
* @return value of url.
*/
public String getUrl() {
return url;
}
/**
* Gets the value of default user (login or user name).
*
* @return value of user.
*/
public String getUser() {
return userName;
}
/**
* Returns the value of the accessToUnderlyingConnectionAllowed property.
*
* @return true if access to the underlying is allowed, false otherwise.
*/
public synchronized boolean isAccessToUnderlyingConnectionAllowed() {
return this.accessToUnderlyingConnectionAllowed;
}
private boolean isNotEmpty(RefAddr ra) {
return ra != null && ra.getContent() != null;
}
/**
* Whether to toggle the pooling of <code>PreparedStatement</code>s
*
* @return value of poolPreparedStatements.
*/
public boolean isPoolPreparedStatements() {
return poolPreparedStatements;
}
/**
* Sets the value of the accessToUnderlyingConnectionAllowed property. It controls if the PoolGuard allows access to
* the underlying connection. (Default: false)
*
* @param allow
* Access to the underlying connection is granted when true.
*/
public synchronized void setAccessToUnderlyingConnectionAllowed(final boolean allow) {
this.accessToUnderlyingConnectionAllowed = allow;
}
/**
* Sets the connection properties passed to the JDBC driver.
* <p>
* If <code>props</code> contains "user" and/or "password" properties, the corresponding instance properties are
* set. If these properties are not present, they are filled in using {@link #getUser()}, {@link #getPassword()}
* when {@link #getPooledConnection()} is called, or using the actual parameters to the method call when
* {@link #getPooledConnection(String, String)} is called. Calls to {@link #setUser(String)} or
* {@link #setPassword(String)} overwrite the values of these properties if <code>connectionProperties</code> is not
* null.
* </p>
*
* @param props
* Connection properties to use when creating new connections.
* @throws IllegalStateException
* if {@link #getPooledConnection()} has been called
*/
public void setConnectionProperties(final Properties props) {
assertInitializationAllowed();
connectionProperties = props;
if (connectionProperties != null) {
if (connectionProperties.containsKey(KEY_USER)) {
setUser(connectionProperties.getProperty(KEY_USER));
}
if (connectionProperties.containsKey(KEY_PASSWORD)) {
setPassword(connectionProperties.getProperty(KEY_PASSWORD));
}
}
}
/**
* Sets the value of description. This property is here for use by the code which will deploy this datasource. It is
* not used internally.
*
* @param v
* Value to assign to description.
*/
public void setDescription(final String v) {
this.description = v;
}
/**
* Sets the driver class name. Setting the driver class name cause the driver to be registered with the
* DriverManager.
*
* @param v
* Value to assign to driver.
* @throws IllegalStateException
* if {@link #getPooledConnection()} has been called
* @throws ClassNotFoundException
* if the class cannot be located
*/
public void setDriver(final String v) throws ClassNotFoundException {
assertInitializationAllowed();
this.driver = v;
// make sure driver is registered
Class.forName(v);
}
/**
* Sets the maximum time in seconds that this data source will wait while attempting to connect to a database. NOT
* USED.
*/
@Override
public void setLoginTimeout(final int seconds) {
loginTimeout = seconds;
}
/**
* Sets the log writer for this data source. NOT USED.
*/
@Override
public void setLogWriter(final PrintWriter out) {
logWriter = out;
}
/**
* Gets the maximum number of statements that can remain idle in the pool, without extra ones being released, or
* negative for no limit.
*
* @param maxIdle
* The maximum number of statements that can remain idle
* @throws IllegalStateException
* if {@link #getPooledConnection()} has been called
*/
public void setMaxIdle(final int maxIdle) {
assertInitializationAllowed();
this.maxIdle = maxIdle;
}
/**
* Sets the maximum number of prepared statements.
*
* @param maxPreparedStatements
* the new maximum number of prepared statements
*/
public void setMaxPreparedStatements(final int maxPreparedStatements) {
this.maxPreparedStatements = maxPreparedStatements;
}
/**
* Sets the minimum amount of time a statement may sit idle in the pool before it is eligible 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.
*
* @param minEvictableIdleTimeMillis
* minimum time to set (in ms)
* @see #getMinEvictableIdleTimeMillis()
* @see #setTimeBetweenEvictionRunsMillis(long)
* @throws IllegalStateException
* if {@link #getPooledConnection()} has been called
*/
public void setMinEvictableIdleTimeMillis(final int minEvictableIdleTimeMillis) {
assertInitializationAllowed();
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
/**
* Sets the number of statements to examine during each run of the idle object evictor thread (if any).
* <p>
* When a negative value is supplied, <code>ceil({*link #numIdle})/abs({*link #getNumTestsPerEvictionRun})</code>
* tests will be run. I.e., when the value is <i>-n</i>, roughly one <i>n</i>th of the idle objects will be tested
* per run.
* </p>
*
* @param numTestsPerEvictionRun
* number of statements to examine per run
* @see #getNumTestsPerEvictionRun()
* @see #setTimeBetweenEvictionRunsMillis(long)
* @throws IllegalStateException
* if {@link #getPooledConnection()} has been called
*/
public void setNumTestsPerEvictionRun(final int numTestsPerEvictionRun) {
assertInitializationAllowed();
this.numTestsPerEvictionRun = numTestsPerEvictionRun;
}
/**
* Sets the value of password for the default user.
*
* @param userPassword
* Value to assign to password.
* @throws IllegalStateException
* if {@link #getPooledConnection()} has been called
*/
public void setPassword(final char[] userPassword) {
assertInitializationAllowed();
this.userPassword = Utils.clone(userPassword);
update(connectionProperties, KEY_PASSWORD, Utils.toString(this.userPassword));
}
/**
* Sets the value of password for the default user.
*
* @param userPassword
* Value to assign to password.
* @throws IllegalStateException
* if {@link #getPooledConnection()} has been called
*/
public void setPassword(final String userPassword) {
assertInitializationAllowed();
this.userPassword = Utils.toCharArray(userPassword);
update(connectionProperties, KEY_PASSWORD, userPassword);
}
/**
* Whether to toggle the pooling of <code>PreparedStatement</code>s
*
* @param poolPreparedStatements
* true to pool statements.
* @throws IllegalStateException
* if {@link #getPooledConnection()} has been called
*/
public void setPoolPreparedStatements(final boolean poolPreparedStatements) {
assertInitializationAllowed();
this.poolPreparedStatements = poolPreparedStatements;
}
/**
* 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.
*
* @param timeBetweenEvictionRunsMillis
* 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 #getTimeBetweenEvictionRunsMillis()
* @throws IllegalStateException
* if {@link #getPooledConnection()} has been called
*/
public void setTimeBetweenEvictionRunsMillis(final long timeBetweenEvictionRunsMillis) {
assertInitializationAllowed();
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
/**
* Sets the value of URL string used to locate the database for this datasource.
*
* @param v
* Value to assign to url.
* @throws IllegalStateException
* if {@link #getPooledConnection()} has been called
*/
public void setUrl(final String v) {
assertInitializationAllowed();
this.url = v;
}
/**
* Sets the value of default user (login or user name).
*
* @param v
* Value to assign to user.
* @throws IllegalStateException
* if {@link #getPooledConnection()} has been called
*/
public void setUser(final String v) {
assertInitializationAllowed();
this.userName = v;
update(connectionProperties, KEY_USER, v);
}
/**
* Does not print the userName and userPassword field nor the 'user' or 'password' in the connectionProperties.
*
* @since 2.6.0
*/
@Override
public synchronized String toString() {
final StringBuilder builder = new StringBuilder(super.toString());
builder.append("[description=");
builder.append(description);
builder.append(", url=");
// TODO What if the connection string contains a 'user' or 'password' query parameter but that connection string is not in a legal URL format?
builder.append(url);
builder.append(", driver=");
builder.append(driver);
builder.append(", loginTimeout=");
builder.append(loginTimeout);
builder.append(", poolPreparedStatements=");
builder.append(poolPreparedStatements);
builder.append(", maxIdle=");
builder.append(maxIdle);
builder.append(", timeBetweenEvictionRunsMillis=");
builder.append(timeBetweenEvictionRunsMillis);
builder.append(", numTestsPerEvictionRun=");
builder.append(numTestsPerEvictionRun);
builder.append(", minEvictableIdleTimeMillis=");
builder.append(minEvictableIdleTimeMillis);
builder.append(", maxPreparedStatements=");
builder.append(maxPreparedStatements);
builder.append(", getConnectionCalled=");
builder.append(getConnectionCalled);
builder.append(", connectionProperties=");
Properties tmpProps = connectionProperties;
final String pwdKey = "password";
if (connectionProperties != null && connectionProperties.contains(pwdKey)) {
tmpProps = (Properties) connectionProperties.clone();
tmpProps.remove(pwdKey);
}
builder.append(tmpProps);
builder.append(", accessToUnderlyingConnectionAllowed=");
builder.append(accessToUnderlyingConnectionAllowed);
builder.append("]");
return builder.toString();
}
private void update(final Properties properties, final String key, final String value) {
if (properties != null && key != null) {
if (value == null) {
properties.remove(key);
} else {
properties.setProperty(key, value);
}
}
}
}

View File

@@ -0,0 +1,113 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.dbcp.dbcp2.cpdsadapter;
import org.apache.tomcat.dbcp.dbcp2.PStmtKey;
/**
* A key uniquely identifying a {@link java.sql.PreparedStatement PreparedStatement}.
*
* @since 2.0
* @deprecated Use {@link PStmtKey}.
*/
@Deprecated
public class PStmtKeyCPDS extends PStmtKey {
/**
* Constructs a key to uniquely identify a prepared statement.
*
* @param sql
* The SQL statement.
*/
public PStmtKeyCPDS(final String sql) {
super(sql);
}
/**
* Constructs a key to uniquely identify a prepared statement.
*
* @param sql
* The SQL statement.
* @param autoGeneratedKeys
* A flag indicating whether auto-generated keys should be returned; one of
* <code>Statement.RETURN_GENERATED_KEYS</code> or <code>Statement.NO_GENERATED_KEYS</code>.
*/
public PStmtKeyCPDS(final String sql, final int autoGeneratedKeys) {
super(sql, null, autoGeneratedKeys);
}
/**
* Constructs a key to uniquely identify a prepared statement.
*
* @param sql
* The SQL statement.
* @param resultSetType
* A result set type; one of <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>.
* @param resultSetConcurrency
* A concurrency type; one of <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>.
*/
public PStmtKeyCPDS(final String sql, final int resultSetType, final int resultSetConcurrency) {
super(sql, resultSetType, resultSetConcurrency);
}
/**
* Constructs a key to uniquely identify a prepared statement.
*
* @param sql
* The SQL statement.
* @param resultSetType
* a result set type; one of <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>.
* @param resultSetConcurrency
* A concurrency type; one of <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>
* @param resultSetHoldability
* One of the following <code>ResultSet</code> constants: <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code>
* or <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>.
*/
public PStmtKeyCPDS(final String sql, final int resultSetType, final int resultSetConcurrency,
final int resultSetHoldability) {
super(sql, null, resultSetType, resultSetConcurrency, resultSetHoldability);
}
/**
* Constructs a key to uniquely identify a prepared statement.
*
* @param sql
* The SQL statement.
* @param columnIndexes
* An array of column indexes indicating the columns that should be returned from the inserted row or
* rows.
*/
public PStmtKeyCPDS(final String sql, final int columnIndexes[]) {
super(sql, null, columnIndexes);
}
/**
* Constructs a key to uniquely identify a prepared statement.
*
* @param sql
* The SQL statement.
* @param columnNames
* An array of column names indicating the columns that should be returned from the inserted row or rows.
*/
public PStmtKeyCPDS(final String sql, final String columnNames[]) {
super(sql, null, columnNames);
}
}

View File

@@ -0,0 +1,731 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.dbcp.dbcp2.cpdsadapter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Vector;
import javax.sql.ConnectionEvent;
import javax.sql.ConnectionEventListener;
import javax.sql.PooledConnection;
import javax.sql.StatementEventListener;
import org.apache.tomcat.dbcp.dbcp2.DelegatingConnection;
import org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement;
import org.apache.tomcat.dbcp.dbcp2.Jdbc41Bridge;
import org.apache.tomcat.dbcp.dbcp2.PStmtKey;
import org.apache.tomcat.dbcp.dbcp2.PoolableCallableStatement;
import org.apache.tomcat.dbcp.dbcp2.PoolablePreparedStatement;
import org.apache.tomcat.dbcp.dbcp2.PoolingConnection.StatementType;
import org.apache.tomcat.dbcp.pool2.KeyedObjectPool;
import org.apache.tomcat.dbcp.pool2.KeyedPooledObjectFactory;
import org.apache.tomcat.dbcp.pool2.PooledObject;
import org.apache.tomcat.dbcp.pool2.impl.DefaultPooledObject;
/**
* Implementation of PooledConnection that is returned by PooledConnectionDataSource.
*
* @since 2.0
*/
class PooledConnectionImpl
implements PooledConnection, KeyedPooledObjectFactory<PStmtKey, DelegatingPreparedStatement> {
private static final String CLOSED = "Attempted to use PooledConnection after closed() was called.";
/**
* The JDBC database connection that represents the physical db connection.
*/
private Connection connection;
/**
* A DelegatingConnection used to create a PoolablePreparedStatementStub.
*/
private final DelegatingConnection<?> delegatingConnection;
/**
* The JDBC database logical connection.
*/
private Connection logicalConnection;
/**
* ConnectionEventListeners.
*/
private final Vector<ConnectionEventListener> eventListeners;
/**
* StatementEventListeners.
*/
private final Vector<StatementEventListener> statementEventListeners = new Vector<>();
/**
* Flag set to true, once {@link #close()} is called.
*/
private boolean closed;
/** My pool of {@link PreparedStatement}s. */
private KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> pStmtPool;
/**
* Controls access to the underlying connection.
*/
private boolean accessToUnderlyingConnectionAllowed;
/**
* Wraps the real connection.
*
* @param connection
* the connection to be wrapped.
*/
PooledConnectionImpl(final Connection connection) {
this.connection = connection;
if (connection instanceof DelegatingConnection) {
this.delegatingConnection = (DelegatingConnection<?>) connection;
} else {
this.delegatingConnection = new DelegatingConnection<>(connection);
}
eventListeners = new Vector<>();
closed = false;
}
/**
* My {@link KeyedPooledObjectFactory} method for activating {@link PreparedStatement}s.
*
* @param key
* Ignored.
* @param pooledObject
* Ignored.
*/
@Override
public void activateObject(final PStmtKey key, final PooledObject<DelegatingPreparedStatement> pooledObject)
throws Exception {
pooledObject.getObject().activate();
}
/**
* {@inheritDoc}
*/
@Override
public void addConnectionEventListener(final ConnectionEventListener listener) {
if (!eventListeners.contains(listener)) {
eventListeners.add(listener);
}
}
/* JDBC_4_ANT_KEY_BEGIN */
@Override
public void addStatementEventListener(final StatementEventListener listener) {
if (!statementEventListeners.contains(listener)) {
statementEventListeners.add(listener);
}
}
/* JDBC_4_ANT_KEY_END */
/**
* Throws an SQLException, if isClosed is true
*/
private void assertOpen() throws SQLException {
if (closed) {
throw new SQLException(CLOSED);
}
}
/**
* Closes the physical connection and marks this <code>PooledConnection</code> so that it may not be used to
* generate any more logical <code>Connection</code>s.
*
* @throws SQLException
* Thrown when an error occurs or the connection is already closed.
*/
@Override
public void close() throws SQLException {
assertOpen();
closed = true;
try {
if (pStmtPool != null) {
try {
pStmtPool.close();
} finally {
pStmtPool = null;
}
}
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new SQLException("Cannot close connection (return to pool failed)", e);
} finally {
try {
connection.close();
} finally {
connection = null;
}
}
}
/**
* Creates a {@link PStmtKey} for the given arguments.
*
* @param sql
* The SQL statement.
* @return a {@link PStmtKey} for the given arguments.
*/
protected PStmtKey createKey(final String sql) {
return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull());
}
/**
* Creates a {@link PStmtKey} for the given arguments.
*
* @param sql
* The SQL statement.
* @param autoGeneratedKeys
* A flag indicating whether auto-generated keys should be returned; one of
* <code>Statement.RETURN_GENERATED_KEYS</code> or <code>Statement.NO_GENERATED_KEYS</code>.
* @return a key to uniquely identify a prepared statement.
*/
protected PStmtKey createKey(final String sql, final int autoGeneratedKeys) {
return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), autoGeneratedKeys);
}
/**
* Creates a {@link PStmtKey} for the given arguments.
*
* @param sql
* The SQL statement.
* @param columnIndexes
* An array of column indexes indicating the columns that should be returned from the inserted row or
* rows.
* @return a key to uniquely identify a prepared statement.
*/
protected PStmtKey createKey(final String sql, final int columnIndexes[]) {
return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), columnIndexes);
}
/**
* Creates a {@link PStmtKey} for the given arguments.
*
* @param sql
* The SQL statement.
* @param resultSetType
* A result set type; one of <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>.
* @param resultSetConcurrency
* A concurrency type; one of <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>.
* @return a key to uniquely identify a prepared statement.
*/
protected PStmtKey createKey(final String sql, final int resultSetType, final int resultSetConcurrency) {
return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), resultSetType,
resultSetConcurrency);
}
/**
* Creates a {@link PStmtKey} for the given arguments.
*
* @param sql
* The SQL statement.
* @param resultSetType
* a result set type; one of <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>.
* @param resultSetConcurrency
* A concurrency type; one of <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>
* @param resultSetHoldability
* One of the following <code>ResultSet</code> constants: <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code>
* or <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>.
* @return a key to uniquely identify a prepared statement.
*/
protected PStmtKey createKey(final String sql, final int resultSetType, final int resultSetConcurrency,
final int resultSetHoldability) {
return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), resultSetType,
resultSetConcurrency, resultSetHoldability);
}
/**
* Creates a {@link PStmtKey} for the given arguments.
*
* @param sql
* The SQL statement.
* @param resultSetType
* a result set type; one of <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
* @param resultSetConcurrency
* A concurrency type; one of <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>.
* @param resultSetHoldability
* One of the following <code>ResultSet</code> constants: <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code>
* or <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>.
* @param statementType
* The SQL statement type, prepared or callable.
* @return a key to uniquely identify a prepared statement.
* @since 2.4.0
*/
protected PStmtKey createKey(final String sql, final int resultSetType, final int resultSetConcurrency,
final int resultSetHoldability, final StatementType statementType) {
return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), resultSetType,
resultSetConcurrency, resultSetHoldability, statementType);
}
/**
* Creates a {@link PStmtKey} for the given arguments.
*
* @param sql
* The SQL statement.
* @param resultSetType
* A result set type; one of <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>.
* @param resultSetConcurrency
* A concurrency type; one of <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>.
* @param statementType
* The SQL statement type, prepared or callable.
* @return a key to uniquely identify a prepared statement.
* @since 2.4.0
*/
protected PStmtKey createKey(final String sql, final int resultSetType, final int resultSetConcurrency,
final StatementType statementType) {
return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), resultSetType,
resultSetConcurrency, statementType);
}
/**
* Creates a {@link PStmtKey} for the given arguments.
*
* @param sql
* The SQL statement.
* @param statementType
* The SQL statement type, prepared or callable.
* @return a key to uniquely identify a prepared statement.
*/
protected PStmtKey createKey(final String sql, final StatementType statementType) {
return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), statementType);
}
/**
* Creates a {@link PStmtKey} for the given arguments.
*
* @param sql
* The SQL statement.
* @param columnNames
* An array of column names indicating the columns that should be returned from the inserted row or rows.
* @return a key to uniquely identify a prepared statement.
*/
protected PStmtKey createKey(final String sql, final String columnNames[]) {
return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), getSchemaOrNull(), columnNames);
}
/**
* My {@link KeyedPooledObjectFactory} method for destroying {@link PreparedStatement}s.
*
* @param key
* ignored
* @param pooledObject
* the wrapped {@link PreparedStatement} to be destroyed.
*/
@Override
public void destroyObject(final PStmtKey key, final PooledObject<DelegatingPreparedStatement> pooledObject)
throws Exception {
pooledObject.getObject().getInnermostDelegate().close();
}
/**
* Closes the physical connection and checks that the logical connection was closed as well.
*/
@Override
protected void finalize() throws Throwable {
// Closing the Connection ensures that if anyone tries to use it,
// an error will occur.
try {
connection.close();
} catch (final Exception ignored) {
// ignore
}
// make sure the last connection is marked as closed
if (logicalConnection != null && !logicalConnection.isClosed()) {
throw new SQLException("PooledConnection was gc'ed, without its last Connection being closed.");
}
}
private String getCatalogOrNull() {
try {
return connection == null ? null : connection.getCatalog();
} catch (final SQLException e) {
return null;
}
}
private String getSchemaOrNull() {
try {
return connection == null ? null : Jdbc41Bridge.getSchema(connection);
} catch (final SQLException e) {
return null;
}
}
/**
* Returns a JDBC connection.
*
* @return The database connection.
* @throws SQLException
* if the connection is not open or the previous logical connection is still open
*/
@Override
public Connection getConnection() throws SQLException {
assertOpen();
// make sure the last connection is marked as closed
if (logicalConnection != null && !logicalConnection.isClosed()) {
// should notify pool of error so the pooled connection can
// be removed !FIXME!
throw new SQLException("PooledConnection was reused, without its previous Connection being closed.");
}
// the spec requires that this return a new Connection instance.
logicalConnection = new ConnectionImpl(this, connection, isAccessToUnderlyingConnectionAllowed());
return logicalConnection;
}
/**
* Returns the value of the accessToUnderlyingConnectionAllowed property.
*
* @return true if access to the underlying is allowed, false otherwise.
*/
public synchronized boolean isAccessToUnderlyingConnectionAllowed() {
return this.accessToUnderlyingConnectionAllowed;
}
/**
* My {@link KeyedPooledObjectFactory} method for creating {@link PreparedStatement}s.
*
* @param key
* The key for the {@link PreparedStatement} to be created.
*/
@SuppressWarnings("resource")
@Override
public PooledObject<DelegatingPreparedStatement> makeObject(final PStmtKey key) throws Exception {
if (null == key) {
throw new IllegalArgumentException("Prepared statement key is null or invalid.");
}
if (key.getStmtType() == StatementType.PREPARED_STATEMENT) {
final PreparedStatement statement = (PreparedStatement) key.createStatement(connection);
@SuppressWarnings({"rawtypes", "unchecked" }) // Unable to find way to avoid this
final PoolablePreparedStatement pps = new PoolablePreparedStatement(statement, key, pStmtPool,
delegatingConnection);
return new DefaultPooledObject<DelegatingPreparedStatement>(pps);
}
final CallableStatement statement = (CallableStatement) key.createStatement(connection);
@SuppressWarnings("unchecked")
final PoolableCallableStatement pcs = new PoolableCallableStatement(statement, key, pStmtPool,
(DelegatingConnection<Connection>) delegatingConnection);
return new DefaultPooledObject<DelegatingPreparedStatement>(pcs);
}
/**
* Normalizes the given SQL statement, producing a canonical form that is semantically equivalent to the original.
* @param sql
* The SQL statement.
* @return the normalized SQL statement.
*/
protected String normalizeSQL(final String sql) {
return sql.trim();
}
/**
* Sends a connectionClosed event.
*/
void notifyListeners() {
final ConnectionEvent event = new ConnectionEvent(this);
final Object[] listeners = eventListeners.toArray();
for (final Object listener : listeners) {
((ConnectionEventListener) listener).connectionClosed(event);
}
}
/**
* My {@link KeyedPooledObjectFactory} method for passivating {@link PreparedStatement}s. Currently invokes
* {@link PreparedStatement#clearParameters}.
*
* @param key
* ignored
* @param pooledObject
* a wrapped {@link PreparedStatement}
*/
@Override
public void passivateObject(final PStmtKey key, final PooledObject<DelegatingPreparedStatement> pooledObject)
throws Exception {
@SuppressWarnings("resource")
final DelegatingPreparedStatement dps = pooledObject.getObject();
dps.clearParameters();
dps.passivate();
}
/**
* Creates or obtains a {@link CallableStatement} from my pool.
*
* @param sql
* an SQL statement that may contain one or more '?' parameter placeholders. Typically this statement is
* specified using JDBC call escape syntax.
* @return a default <code>CallableStatement</code> object containing the pre-compiled SQL statement.
* @exception SQLException
* Thrown if a database access error occurs or this method is called on a closed connection.
* @since 2.4.0
*/
CallableStatement prepareCall(final String sql) throws SQLException {
if (pStmtPool == null) {
return connection.prepareCall(sql);
}
try {
return (CallableStatement) pStmtPool.borrowObject(createKey(sql, StatementType.CALLABLE_STATEMENT));
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new SQLException("Borrow prepareCall from pool failed", e);
}
}
/**
* Creates or obtains a {@link CallableStatement} from my pool.
*
* @param sql
* a <code>String</code> object that is the SQL statement to be sent to the database; may contain on or
* more '?' parameters.
* @param resultSetType
* a result set type; one of <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>.
* @param resultSetConcurrency
* a concurrency type; one of <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>.
* @return a <code>CallableStatement</code> object containing the pre-compiled SQL statement that will produce
* <code>ResultSet</code> objects with the given type and concurrency.
* @throws SQLException
* Thrown if a database access error occurs, this method is called on a closed connection or the given
* parameters are not <code>ResultSet</code> constants indicating type and concurrency.
* @since 2.4.0
*/
CallableStatement prepareCall(final String sql, final int resultSetType, final int resultSetConcurrency)
throws SQLException {
if (pStmtPool == null) {
return connection.prepareCall(sql, resultSetType, resultSetConcurrency);
}
try {
return (CallableStatement) pStmtPool.borrowObject(
createKey(sql, resultSetType, resultSetConcurrency, StatementType.CALLABLE_STATEMENT));
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new SQLException("Borrow prepareCall from pool failed", e);
}
}
/**
* Creates or obtains a {@link CallableStatement} from my pool.
*
* @param sql
* a <code>String</code> object that is the SQL statement to be sent to the database; may contain on or
* more '?' parameters.
* @param resultSetType
* one of the following <code>ResultSet</code> constants: <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>.
* @param resultSetConcurrency
* one of the following <code>ResultSet</code> constants: <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>.
* @param resultSetHoldability
* one of the following <code>ResultSet</code> constants: <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code>
* or <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>.
* @return a new <code>CallableStatement</code> object, containing the pre-compiled SQL statement, that will
* generate <code>ResultSet</code> objects with the given type, concurrency, and holdability.
* @throws SQLException
* Thrown if a database access error occurs, this method is called on a closed connection or the given
* parameters are not <code>ResultSet</code> constants indicating type, concurrency, and holdability.
* @since 2.4.0
*/
CallableStatement prepareCall(final String sql, final int resultSetType, final int resultSetConcurrency,
final int resultSetHoldability) throws SQLException {
if (pStmtPool == null) {
return connection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
}
try {
return (CallableStatement) pStmtPool.borrowObject(createKey(sql, resultSetType, resultSetConcurrency,
resultSetHoldability, StatementType.CALLABLE_STATEMENT));
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new SQLException("Borrow prepareCall from pool failed", e);
}
}
/**
* Creates or obtains a {@link PreparedStatement} from my pool.
*
* @param sql
* the SQL statement.
* @return a {@link PoolablePreparedStatement}
*/
PreparedStatement prepareStatement(final String sql) throws SQLException {
if (pStmtPool == null) {
return connection.prepareStatement(sql);
}
try {
return pStmtPool.borrowObject(createKey(sql));
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new SQLException("Borrow prepareStatement from pool failed", e);
}
}
/**
* Creates or obtains a {@link PreparedStatement} from my pool.
*
* @param sql
* an SQL statement that may contain one or more '?' IN parameter placeholders.
* @param autoGeneratedKeys
* a flag indicating whether auto-generated keys should be returned; one of
* <code>Statement.RETURN_GENERATED_KEYS</code> or <code>Statement.NO_GENERATED_KEYS</code>.
* @return a {@link PoolablePreparedStatement}
* @see Connection#prepareStatement(String, int)
*/
PreparedStatement prepareStatement(final String sql, final int autoGeneratedKeys) throws SQLException {
if (pStmtPool == null) {
return connection.prepareStatement(sql, autoGeneratedKeys);
}
try {
return pStmtPool.borrowObject(createKey(sql, autoGeneratedKeys));
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new SQLException("Borrow prepareStatement from pool failed", e);
}
}
PreparedStatement prepareStatement(final String sql, final int columnIndexes[]) throws SQLException {
if (pStmtPool == null) {
return connection.prepareStatement(sql, columnIndexes);
}
try {
return pStmtPool.borrowObject(createKey(sql, columnIndexes));
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new SQLException("Borrow prepareStatement from pool failed", e);
}
}
/**
* Creates or obtains a {@link PreparedStatement} from my pool.
*
* @param sql
* a <code>String</code> object that is the SQL statement to be sent to the database; may contain one or
* more '?' IN parameters.
* @param resultSetType
* a result set type; one of <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>.
* @param resultSetConcurrency
* a concurrency type; one of <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>.
*
* @return a {@link PoolablePreparedStatement}.
* @see Connection#prepareStatement(String, int, int)
*/
PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency)
throws SQLException {
if (pStmtPool == null) {
return connection.prepareStatement(sql, resultSetType, resultSetConcurrency);
}
try {
return pStmtPool.borrowObject(createKey(sql, resultSetType, resultSetConcurrency));
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new SQLException("Borrow prepareStatement from pool failed", e);
}
}
PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency,
final int resultSetHoldability) throws SQLException {
if (pStmtPool == null) {
return connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
}
try {
return pStmtPool.borrowObject(createKey(sql, resultSetType, resultSetConcurrency, resultSetHoldability));
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new SQLException("Borrow prepareStatement from pool failed", e);
}
}
PreparedStatement prepareStatement(final String sql, final String columnNames[]) throws SQLException {
if (pStmtPool == null) {
return connection.prepareStatement(sql, columnNames);
}
try {
return pStmtPool.borrowObject(createKey(sql, columnNames));
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new SQLException("Borrow prepareStatement from pool failed", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void removeConnectionEventListener(final ConnectionEventListener listener) {
eventListeners.remove(listener);
}
/* JDBC_4_ANT_KEY_BEGIN */
@Override
public void removeStatementEventListener(final StatementEventListener listener) {
statementEventListeners.remove(listener);
}
/* JDBC_4_ANT_KEY_END */
/**
* Sets the value of the accessToUnderlyingConnectionAllowed property. It controls if the PoolGuard allows access to
* the underlying connection. (Default: false.)
*
* @param allow
* Access to the underlying connection is granted when true.
*/
public synchronized void setAccessToUnderlyingConnectionAllowed(final boolean allow) {
this.accessToUnderlyingConnectionAllowed = allow;
}
public void setStatementPool(final KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> statementPool) {
pStmtPool = statementPool;
}
/**
* My {@link KeyedPooledObjectFactory} method for validating {@link PreparedStatement}s.
*
* @param key
* Ignored.
* @param pooledObject
* Ignored.
* @return {@code true}
*/
@Override
public boolean validateObject(final PStmtKey key, final PooledObject<DelegatingPreparedStatement> pooledObject) {
return true;
}
}

View File

@@ -0,0 +1,79 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* <p>
* This package contains one public class which is a
* <code>ConnectionPoolDataSource</code> (CPDS) implementation that can be used to
* adapt older <code>Driver</code> based JDBC implementations. Below is an
* example of setting up the CPDS to be available via JNDI in the
* catalina servlet container.
* </p>
* <p>In server.xml, the following would be added to the &lt;Context&gt; for your
* webapp:
* </p>
*
* <pre>
* &lt;Resource name="jdbc/bookstoreCPDS" auth="Container"
* type="org.apache.tomcat.dbcp.dbcp2.cpdsadapter.DriverAdapterCPDS"/&gt;
* &lt;ResourceParams name="jdbc/bookstoreCPDS"&gt;
* &lt;parameter&gt;
* &lt;name&gt;factory&lt;/name&gt;
* &lt;value&gt;org.apache.tomcat.dbcp.dbcp2.cpdsadapter.DriverAdapterCPDS&lt;/value&gt;
* &lt;/parameter&gt;
* &lt;parameter&gt;&lt;name&gt;user&lt;/name&gt;&lt;value&gt;root&lt;/value&gt;&lt;/parameter&gt;
* &lt;parameter&gt;&lt;name&gt;password&lt;/name&gt;&lt;value&gt;&lt;/value&gt;&lt;/parameter&gt;
* &lt;parameter&gt;
* &lt;name&gt;driver&lt;/name&gt;
* &lt;value&gt;org.gjt.mm.mysql.Driver&lt;/value&gt;&lt;/parameter&gt;
* &lt;parameter&gt;
* &lt;name&gt;url&lt;/name&gt;
* &lt;value&gt;jdbc:mysql://localhost:3306/bookstore&lt;/value&gt;
* &lt;/parameter&gt;
* &lt;/ResourceParams&gt;
* </pre>
*
* <p>
* In web.xml. Note that elements must be given in the order of the dtd
* described in the servlet specification:
* </p>
*
* <pre>
* &lt;resource-ref&gt;
* &lt;description&gt;
* Resource reference to a factory for java.sql.Connection
* instances that may be used for talking to a particular
* database that is configured in the server.xml file.
* &lt;/description&gt;
* &lt;res-ref-name&gt;
* jdbc/bookstoreCPDS
* &lt;/res-ref-name&gt;
* &lt;res-type&gt;
* org.apache.tomcat.dbcp.dbcp2.cpdsadapter.DriverAdapterCPDS
* &lt;/res-type&gt;
* &lt;res-auth&gt;
* Container
* &lt;/res-auth&gt;
* &lt;/resource-ref&gt;
* </pre>
*
* <p>
* Catalina deploys all objects configured similarly to above within the
* <strong>java:comp/env</strong> namespace.
* </p>
*/
package org.apache.tomcat.dbcp.dbcp2.cpdsadapter;