Modified: tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/PoolingDataSource.java URL: http://svn.apache.org/viewvc/tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/PoolingDataSource.java?rev=1833816&r1=1833815&r2=1833816&view=diff ============================================================================== --- tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/PoolingDataSource.java (original) +++ tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/PoolingDataSource.java Tue Jun 19 11:21:13 2018 @@ -21,6 +21,7 @@ import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.NoSuchElementException; +import java.util.Objects; import java.util.logging.Logger; import javax.sql.DataSource; @@ -31,15 +32,11 @@ import org.apache.tomcat.dbcp.pool2.Obje import org.apache.tomcat.dbcp.pool2.impl.GenericObjectPool; /** - * A simple {@link DataSource} implementation that obtains - * {@link Connection}s from the specified {@link ObjectPool}. + * A simple {@link DataSource} implementation that obtains {@link Connection}s from the specified {@link ObjectPool}. * - * @param <C> The connection type + * @param <C> + * The connection type * - * @author Rodney Waldhoff - * @author Glenn L. Nielsen - * @author James House - * @author Dirk Verbeeck * @since 2.0 */ public class PoolingDataSource<C extends Connection> implements DataSource, AutoCloseable { @@ -47,40 +44,43 @@ public class PoolingDataSource<C extends private static final Log log = LogFactory.getLog(PoolingDataSource.class); /** Controls access to the underlying connection */ - private boolean accessToUnderlyingConnectionAllowed = false; + private boolean accessToUnderlyingConnectionAllowed; + /** + * Constructs a new instance backed by the given connection pool. + * + * @param pool + * the given connection pool. + */ public PoolingDataSource(final ObjectPool<C> pool) { - if (null == pool) { - throw new NullPointerException("Pool must not be null."); - } - _pool = pool; - // Verify that _pool's factory refers back to it. If not, log a warning and try to fix. - if (_pool instanceof GenericObjectPool<?>) { - final PoolableConnectionFactory pcf = (PoolableConnectionFactory) ((GenericObjectPool<?>) _pool).getFactory(); - if (pcf == null) { - throw new NullPointerException("PoolableConnectionFactory must not be null."); - } - if (pcf.getPool() != _pool) { + Objects.requireNonNull(pool, "Pool must not be null."); + this.pool = pool; + // Verify that pool's factory refers back to it. If not, log a warning and try to fix. + if (this.pool instanceof GenericObjectPool<?>) { + final PoolableConnectionFactory pcf = (PoolableConnectionFactory) ((GenericObjectPool<?>) this.pool) + .getFactory(); + Objects.requireNonNull(pcf, "PoolableConnectionFactory must not be null."); + if (pcf.getPool() != this.pool) { log.warn(Utils.getMessage("poolingDataSource.factoryConfig")); @SuppressWarnings("unchecked") // PCF must have a pool of PCs - final - ObjectPool<PoolableConnection> p = (ObjectPool<PoolableConnection>) _pool; + final ObjectPool<PoolableConnection> p = (ObjectPool<PoolableConnection>) this.pool; pcf.setPool(p); } } } /** - * Close and free all {@link Connection}s from the pool. + * Closes and free all {@link Connection}s from the pool. + * * @since 2.1 */ @Override public void close() throws Exception { try { - _pool.close(); - } catch(final RuntimeException rte) { + pool.close(); + } catch (final RuntimeException rte) { throw new RuntimeException(Utils.getMessage("pool.close.fail"), rte); - } catch(final Exception e) { + } catch (final Exception e) { throw new SQLException(Utils.getMessage("pool.close.fail"), e); } } @@ -95,11 +95,11 @@ public class PoolingDataSource<C extends } /** - * Sets the value of the accessToUnderlyingConnectionAllowed property. - * It controls if the PoolGuard allows access to the underlying connection. - * (Default: false) + * 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. + * @param allow + * Access to the underlying connection is granted when true. */ public void setAccessToUnderlyingConnectionAllowed(final boolean allow) { this.accessToUnderlyingConnectionAllowed = allow; @@ -122,38 +122,40 @@ public class PoolingDataSource<C extends throw new SQLFeatureNotSupportedException(); } - //--- DataSource methods ----------------------------------------- + // --- DataSource methods ----------------------------------------- /** - * Return a {@link java.sql.Connection} from my pool, - * according to the contract specified by {@link ObjectPool#borrowObject}. + * Returns a {@link java.sql.Connection} from my pool, according to the contract specified by + * {@link ObjectPool#borrowObject}. */ @Override public Connection getConnection() throws SQLException { try { - final C conn = _pool.borrowObject(); + final C conn = pool.borrowObject(); if (conn == null) { return null; } return new PoolGuardConnectionWrapper<>(conn); - } catch(final SQLException e) { + } catch (final SQLException e) { throw e; - } catch(final NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new SQLException("Cannot get a connection, pool error " + e.getMessage(), e); - } catch(final RuntimeException e) { + } catch (final RuntimeException e) { throw e; - } catch(final InterruptedException e) { + } catch (final InterruptedException e) { // Reset the interrupt status so it is visible to callers Thread.currentThread().interrupt(); throw new SQLException("Cannot get a connection, general error", e); - } catch(final Exception e) { + } catch (final Exception e) { throw new SQLException("Cannot get a connection, general error", e); } } /** * Throws {@link UnsupportedOperationException} + * * @throws UnsupportedOperationException + * always thrown */ @Override public Connection getConnection(final String uname, final String passwd) throws SQLException { @@ -162,18 +164,20 @@ public class PoolingDataSource<C extends /** * Returns my log writer. + * * @return my log writer * @see DataSource#getLogWriter */ @Override public PrintWriter getLogWriter() { - return _logWriter; + return logWriter; } /** * Throws {@link UnsupportedOperationException}. - * @throws UnsupportedOperationException As this - * implementation does not support this feature. + * + * @throws UnsupportedOperationException + * As this implementation does not support this feature. */ @Override public int getLoginTimeout() { @@ -182,8 +186,9 @@ public class PoolingDataSource<C extends /** * Throws {@link UnsupportedOperationException}. - * @throws UnsupportedOperationException As this - * implementation does not support this feature. + * + * @throws UnsupportedOperationException + * As this implementation does not support this feature. */ @Override public void setLoginTimeout(final int seconds) { @@ -192,29 +197,29 @@ public class PoolingDataSource<C extends /** * Sets my log writer. + * * @see DataSource#setLogWriter */ @Override public void setLogWriter(final PrintWriter out) { - _logWriter = out; + logWriter = out; } /** My log writer. */ - private PrintWriter _logWriter = null; + private PrintWriter logWriter = null; - private final ObjectPool<C> _pool; + private final ObjectPool<C> pool; protected ObjectPool<C> getPool() { - return _pool; + return pool; } /** - * PoolGuardConnectionWrapper is a Connection wrapper that makes sure a - * closed connection cannot be used anymore. + * PoolGuardConnectionWrapper is a Connection wrapper that makes sure a closed connection cannot be used anymore. + * * @since 2.0 */ - private class PoolGuardConnectionWrapper<D extends Connection> - extends DelegatingConnection<D> { + private class PoolGuardConnectionWrapper<D extends Connection> extends DelegatingConnection<D> { PoolGuardConnectionWrapper(final D delegate) { super(delegate); @@ -225,10 +230,7 @@ public class PoolingDataSource<C extends */ @Override public D getDelegate() { - if (isAccessToUnderlyingConnectionAllowed()) { - return super.getDelegate(); - } - return null; + return isAccessToUnderlyingConnectionAllowed() ? super.getDelegate() : null; } /** @@ -236,10 +238,7 @@ public class PoolingDataSource<C extends */ @Override public Connection getInnermostDelegate() { - if (isAccessToUnderlyingConnectionAllowed()) { - return super.getInnermostDelegate(); - } - return null; + return isAccessToUnderlyingConnectionAllowed() ? super.getInnermostDelegate() : null; } @Override @@ -252,10 +251,7 @@ public class PoolingDataSource<C extends @Override public boolean isClosed() throws SQLException { - if (getDelegateInternal() == null) { - return true; - } - return super.isClosed(); + return getDelegateInternal() == null ? true : super.isClosed(); } } }
Modified: tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/PoolingDriver.java URL: http://svn.apache.org/viewvc/tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/PoolingDriver.java?rev=1833816&r1=1833815&r2=1833816&view=diff ============================================================================== --- tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/PoolingDriver.java (original) +++ tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/PoolingDriver.java Tue Jun 19 11:21:13 2018 @@ -30,32 +30,31 @@ import java.util.logging.Logger; import org.apache.tomcat.dbcp.pool2.ObjectPool; - /** - * A {@link Driver} implementation that obtains - * {@link Connection}s from a registered - * {@link ObjectPool}. + * A {@link Driver} implementation that obtains {@link Connection}s from a registered {@link ObjectPool}. * - * @author Rodney Waldhoff - * @author Dirk Verbeeck * @since 2.0 */ public class PoolingDriver implements Driver { + /** Register myself with the {@link DriverManager}. */ static { try { DriverManager.registerDriver(new PoolingDriver()); - } catch(final Exception e) { + } catch (final Exception e) { + // ignore } } /** The map of registered pools. */ - protected static final HashMap<String,ObjectPool<? extends Connection>> pools = - new HashMap<>(); + protected static final HashMap<String, ObjectPool<? extends Connection>> pools = new HashMap<>(); /** Controls access to the underlying connection */ private final boolean accessToUnderlyingConnectionAllowed; + /** + * Constructs a new driver with <code>accessToUnderlyingConnectionAllowed</code> enabled. + */ public PoolingDriver() { this(true); } @@ -67,7 +66,6 @@ public class PoolingDriver implements Dr this.accessToUnderlyingConnectionAllowed = accessToUnderlyingConnectionAllowed; } - /** * Returns the value of the accessToUnderlyingConnectionAllowed property. * @@ -77,52 +75,75 @@ public class PoolingDriver implements Dr return accessToUnderlyingConnectionAllowed; } - public synchronized ObjectPool<? extends Connection> getConnectionPool(final String name) - throws SQLException { + /** + * Gets the connection pool for the given name. + * + * @param name + * The pool name + * @return The pool + * @throws SQLException + * Thrown when the named pool is not registered. + */ + public synchronized ObjectPool<? extends Connection> getConnectionPool(final String name) throws SQLException { final ObjectPool<? extends Connection> pool = pools.get(name); if (null == pool) { - throw new SQLException("Pool not registered."); + throw new SQLException("Pool not registered: " + name); } return pool; } - public synchronized void registerPool(final String name, - final ObjectPool<? extends Connection> pool) { - pools.put(name,pool); + /** + * Registers a named pool. + * + * @param name + * The pool name. + * @param pool + * The pool. + */ + public synchronized void registerPool(final String name, final ObjectPool<? extends Connection> pool) { + pools.put(name, pool); } + /** + * Closes a named pool. + * + * @param name + * The pool name. + * @throws SQLException + * Thrown when a problem is caught closing the pool. + */ public synchronized void closePool(final String name) throws SQLException { + @SuppressWarnings("resource") final ObjectPool<? extends Connection> pool = pools.get(name); if (pool != null) { pools.remove(name); try { pool.close(); - } - catch (final Exception e) { + } catch (final Exception e) { throw new SQLException("Error closing pool " + name, e); } } } - public synchronized String[] getPoolNames(){ + /** + * Gets the pool names. + * + * @return the pool names. + */ + public synchronized String[] getPoolNames() { final Set<String> names = pools.keySet(); return names.toArray(new String[names.size()]); } @Override public boolean acceptsURL(final String url) throws SQLException { - try { - return url.startsWith(URL_PREFIX); - } catch(final NullPointerException e) { - return false; - } + return url == null ? false : url.startsWith(URL_PREFIX); } @Override public Connection connect(final String url, final Properties info) throws SQLException { - if(acceptsURL(url)) { - final ObjectPool<? extends Connection> pool = - getConnectionPool(url.substring(URL_PREFIX_LEN)); + if (acceptsURL(url)) { + final ObjectPool<? extends Connection> pool = getConnectionPool(url.substring(URL_PREFIX_LEN)); try { final Connection conn = pool.borrowObject(); @@ -130,13 +151,13 @@ public class PoolingDriver implements Dr return null; } return new PoolGuardConnectionWrapper(pool, conn); - } catch(final SQLException e) { + } catch (final SQLException e) { throw e; - } catch(final NoSuchElementException e) { + } catch (final NoSuchElementException e) { throw new SQLException("Cannot get a connection, pool error: " + e.getMessage(), e); - } catch(final RuntimeException e) { + } catch (final RuntimeException e) { throw e; - } catch(final Exception e) { + } catch (final Exception e) { throw new SQLException("Cannot get a connection, general error: " + e.getMessage(), e); } } @@ -151,24 +172,23 @@ public class PoolingDriver implements Dr /** * Invalidates the given connection. * - * @param conn connection to invalidate - * @throws SQLException if the connection is not a - * <code>PoolGuardConnectionWrapper</code> or an error occurs invalidating - * the connection + * @param conn + * connection to invalidate + * @throws SQLException + * if the connection is not a <code>PoolGuardConnectionWrapper</code> or an error occurs invalidating + * the connection */ public void invalidateConnection(final Connection conn) throws SQLException { if (conn instanceof PoolGuardConnectionWrapper) { // normal case final PoolGuardConnectionWrapper pgconn = (PoolGuardConnectionWrapper) conn; @SuppressWarnings("unchecked") - final - ObjectPool<Connection> pool = (ObjectPool<Connection>) pgconn.pool; + final ObjectPool<Connection> pool = (ObjectPool<Connection>) pgconn.pool; try { pool.invalidateObject(pgconn.getDelegateInternal()); + } catch (final Exception e) { + // Ignore. } - catch (final Exception e) { - } - } - else { + } else { throw new SQLException("Invalid connection class"); } } @@ -194,7 +214,7 @@ public class PoolingDriver implements Dr } /** My URL prefix */ - protected static final String URL_PREFIX = "jdbc:apache:commons:dbcp:"; + public static final String URL_PREFIX = "jdbc:apache:commons:dbcp:"; protected static final int URL_PREFIX_LEN = URL_PREFIX.length(); // version numbers @@ -202,16 +222,15 @@ public class PoolingDriver implements Dr protected static final int MINOR_VERSION = 0; /** - * PoolGuardConnectionWrapper is a Connection wrapper that makes sure a - * closed connection cannot be used anymore. + * PoolGuardConnectionWrapper is a Connection wrapper that makes sure a closed connection cannot be used anymore. + * * @since 2.0 */ private class PoolGuardConnectionWrapper extends DelegatingConnection<Connection> { private final ObjectPool<? extends Connection> pool; - PoolGuardConnectionWrapper(final ObjectPool<? extends Connection> pool, - final Connection delegate) { + PoolGuardConnectionWrapper(final ObjectPool<? extends Connection> pool, final Connection delegate) { super(delegate); this.pool = pool; } Modified: tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/SwallowedExceptionLogger.java URL: http://svn.apache.org/viewvc/tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/SwallowedExceptionLogger.java?rev=1833816&r1=1833815&r2=1833816&view=diff ============================================================================== --- tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/SwallowedExceptionLogger.java (original) +++ tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/SwallowedExceptionLogger.java Tue Jun 19 11:21:13 2018 @@ -21,29 +21,31 @@ import org.apache.tomcat.dbcp.pool2.Swal /** * Class for logging swallowed exceptions. + * * @since 2.0 */ -public class SwallowedExceptionLogger implements SwallowedExceptionListener{ +public class SwallowedExceptionLogger implements SwallowedExceptionListener { private final Log log; private final boolean logExpiredConnections; /** - * Create a SwallowedExceptionLogger with the given logger. By default, - * expired connection logging is turned on. + * Create a SwallowedExceptionLogger with the given logger. By default, expired connection logging is turned on. * - * @param log logger + * @param log + * logger */ public SwallowedExceptionLogger(final Log log) { this(log, true); } /** - * Create a SwallowedExceptionLogger with the given logger and expired - * connection logging property. + * Create a SwallowedExceptionLogger with the given logger and expired connection logging property. * - * @param log logger - * @param logExpiredConnections false suppresses logging of expired connection events + * @param log + * logger + * @param logExpiredConnections + * false suppresses logging of expired connection events */ public SwallowedExceptionLogger(final Log log, final boolean logExpiredConnections) { this.log = log; @@ -53,8 +55,7 @@ public class SwallowedExceptionLogger im @Override public void onSwallowException(final Exception e) { if (logExpiredConnections || !(e instanceof LifetimeExceededException)) { - log.warn(Utils.getMessage( - "swallowedExceptionLogger.onSwallowedException"), e); + log.warn(Utils.getMessage("swallowedExceptionLogger.onSwallowedException"), e); } } } Modified: tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/Utils.java URL: http://svn.apache.org/viewvc/tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/Utils.java?rev=1833816&r1=1833815&r2=1833816&view=diff ============================================================================== --- tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/Utils.java (original) +++ tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/Utils.java Tue Jun 19 11:21:13 2018 @@ -28,15 +28,18 @@ import java.util.Set; /** * Utility methods. + * * @since 2.0 */ public final class Utils { - private static final ResourceBundle messages = ResourceBundle.getBundle( - Utils.class.getPackage().getName() + ".LocalStrings"); + private static final ResourceBundle messages = ResourceBundle + .getBundle(Utils.class.getPackage().getName() + ".LocalStrings"); - public static final boolean IS_SECURITY_ENABLED = - System.getSecurityManager() != null; + /** + * Whether the security manager is enabled. + */ + public static final boolean IS_SECURITY_ENABLED = System.getSecurityManager() != null; /** Any SQL_STATE starting with this value is considered a fatal disconnect */ public static final String DISCONNECTION_SQL_CODE_PREFIX = "08"; @@ -44,12 +47,12 @@ public final class Utils { /** * SQL codes of fatal connection errors. * <ul> - * <li>57P01 (ADMIN SHUTDOWN)</li> - * <li>57P02 (CRASH SHUTDOWN)</li> - * <li>57P03 (CANNOT CONNECT NOW)</li> - * <li>01002 (SQL92 disconnect error)</li> - * <li>JZ0C0 (Sybase disconnect error)</li> - * <li>JZ0C1 (Sybase disconnect error)</li> + * <li>57P01 (ADMIN SHUTDOWN)</li> + * <li>57P02 (CRASH SHUTDOWN)</li> + * <li>57P03 (CANNOT CONNECT NOW)</li> + * <li>01002 (SQL92 disconnect error)</li> + * <li>JZ0C0 (Sybase disconnect error)</li> + * <li>JZ0C1 (Sybase disconnect error)</li> * </ul> */ public static final Set<String> DISCONNECTION_SQL_CODES; @@ -71,12 +74,13 @@ public final class Utils { /** * Closes the ResultSet (which may be null). * - * @param rset a ResultSet, may be {@code null} + * @param resultSet + * a ResultSet, may be {@code null} */ - public static void closeQuietly(final ResultSet rset) { - if (rset != null) { + public static void closeQuietly(final ResultSet resultSet) { + if (resultSet != null) { try { - rset.close(); + resultSet.close(); } catch (final Exception e) { // ignored } @@ -86,12 +90,13 @@ public final class Utils { /** * Closes the Connection (which may be null). * - * @param conn a Connection, may be {@code null} + * @param connection + * a Connection, may be {@code null} */ - public static void closeQuietly(final Connection conn) { - if (conn != null) { + public static void closeQuietly(final Connection connection) { + if (connection != null) { try { - conn.close(); + connection.close(); } catch (final Exception e) { // ignored } @@ -101,37 +106,67 @@ public final class Utils { /** * Closes the Statement (which may be null). * - * @param stmt a Statement, may be {@code null} + * @param statement + * a Statement, may be {@code null}. */ - public static void closeQuietly(final Statement stmt) { - if (stmt != null) { + public static void closeQuietly(final Statement statement) { + if (statement != null) { try { - stmt.close(); + statement.close(); } catch (final Exception e) { // ignored } } } - /** - * Obtain the correct i18n message for the given key. + * Gets the correct i18n message for the given key. + * + * @param key + * The key to look up an i18n message. + * @return The i18n message. */ public static String getMessage(final String key) { return getMessage(key, (Object[]) null); } - /** - * Obtain the correct i18n message for the given key with placeholders - * replaced by the supplied arguments. + * Gets the correct i18n message for the given key with placeholders replaced by the supplied arguments. + * + * @param key + * A message key. + * @param args + * The message arguments. + * @return An i18n message. */ public static String getMessage(final String key, final Object... args) { - final String msg = messages.getString(key); + final String msg = messages.getString(key); if (args == null || args.length == 0) { return msg; } final MessageFormat mf = new MessageFormat(msg); return mf.format(args, new StringBuffer(), null).toString(); } + + /** + * Converts the given String to a char[]. + * + * @param value + * may be null. + * @return a char[] or null. + */ + public static char[] toCharArray(final String value) { + return value != null ? value.toCharArray() : null; + } + + /** + * Converts the given char[] to a String. + * + * @param value + * may be null. + * @return a String or null. + */ + public static String toString(final char[] value) { + return value == null ? null : String.valueOf(value); + } } Modified: tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/cpdsadapter/ConnectionImpl.java URL: http://svn.apache.org/viewvc/tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/cpdsadapter/ConnectionImpl.java?rev=1833816&r1=1833815&r2=1833816&view=diff ============================================================================== --- tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/cpdsadapter/ConnectionImpl.java (original) +++ tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/cpdsadapter/ConnectionImpl.java Tue Jun 19 11:21:13 2018 @@ -17,26 +17,25 @@ 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 + * 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> * - * ConnectionImpl extends DelegatingConnection to enable access to the - * underlying connection. - * - * @author John D. McNally * @since 2.0 */ class ConnectionImpl extends DelegatingConnection<Connection> { @@ -44,32 +43,34 @@ class ConnectionImpl extends DelegatingC private final boolean accessToUnderlyingConnectionAllowed; /** The object that instantiated this object */ - private final PooledConnectionImpl pooledConnection; + 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 + * @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, + ConnectionImpl(final PooledConnectionImpl pooledConnection, final Connection connection, final boolean accessToUnderlyingConnectionAllowed) { super(connection); this.pooledConnection = pooledConnection; - this.accessToUnderlyingConnectionAllowed = - accessToUnderlyingConnectionAllowed; + this.accessToUnderlyingConnectionAllowed = accessToUnderlyingConnectionAllowed; } /** - * Marks the Connection as closed, and notifies the pool that the - * pooled connection is available. - * In accordance with the JDBC specification this Connection cannot - * be used after closed() is called. Any further usage will result in an - * SQLException. + * 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. + * @throws SQLException + * The database connection couldn't be closed. */ @Override public void close() throws SQLException { @@ -84,106 +85,179 @@ class ConnectionImpl extends DelegatingC } /** - * 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}. + * 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 SQL statement to be prepared - * @return the prepared statement - * @throws SQLException if this connection is closed or an error occurs - * in the wrapped 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 PreparedStatement prepareStatement(final String sql) throws SQLException { + public CallableStatement prepareCall(final String sql) throws SQLException { checkOpen(); try { - return new DelegatingPreparedStatement - (this, pooledConnection.prepareStatement(sql)); - } - catch (final SQLException e) { + return new DelegatingCallableStatement(this, pooledConnection.prepareCall(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}. + * 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}. * - * @throws SQLException if this connection is closed or an error occurs - * in the wrapped 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 PreparedStatement prepareStatement(final String sql, final int resultSetType, - final int resultSetConcurrency) + public CallableStatement prepareCall(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 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 PreparedStatement prepareStatement(final String sql, final int resultSetType, - final int resultSetConcurrency, - final int resultSetHoldability) - throws SQLException { + public CallableStatement prepareCall(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)); + return new DelegatingCallableStatement(this, + pooledConnection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability)); + } catch (final SQLException e) { + handleException(e); // Does not return + return null; } - catch (final SQLException e) { - handleException(e); + } + + /** + * 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 autoGeneratedKeys) + public PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency) throws SQLException { checkOpen(); try { return new DelegatingPreparedStatement(this, - pooledConnection.prepareStatement(sql, autoGeneratedKeys)); - } - catch (final SQLException e) { + pooledConnection.prepareStatement(sql, resultSetType, resultSetConcurrency)); + } catch (final SQLException e) { handleException(e); return null; } } @Override - public PreparedStatement prepareStatement(final String sql, final int columnIndexes[]) - throws SQLException { + 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, columnIndexes)); + pooledConnection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability)); + } catch (final SQLException e) { + handleException(e); + return null; } - catch (final SQLException e) { + } + + @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 String columnNames[]) - throws SQLException { + public PreparedStatement prepareStatement(final String sql, final int columnIndexes[]) throws SQLException { checkOpen(); try { - return new DelegatingPreparedStatement(this, - pooledConnection.prepareStatement(sql, columnNames)); + return new DelegatingPreparedStatement(this, pooledConnection.prepareStatement(sql, columnIndexes)); + } catch (final SQLException e) { + handleException(e); + return null; } - catch (final SQLException e) { + } + + @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; } @@ -195,6 +269,7 @@ class ConnectionImpl extends DelegatingC /** * If false, getDelegate() and getInnermostDelegate() will return null. + * * @return true if access is allowed to the underlying connection * @see ConnectionImpl */ @@ -204,6 +279,7 @@ class ConnectionImpl extends DelegatingC /** * Get the delegated connection, if allowed. + * * @return the internal connection, or null if access is not allowed. * @see #isAccessToUnderlyingConnectionAllowed() */ @@ -217,6 +293,7 @@ class ConnectionImpl extends DelegatingC /** * Get the innermost connection, if allowed. + * * @return the innermost internal connection, or null if access is not allowed. * @see #isAccessToUnderlyingConnectionAllowed() */ Modified: tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/cpdsadapter/DriverAdapterCPDS.java URL: http://svn.apache.org/viewvc/tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/cpdsadapter/DriverAdapterCPDS.java?rev=1833816&r1=1833815&r2=1833816&view=diff ============================================================================== --- tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/cpdsadapter/DriverAdapterCPDS.java (original) +++ tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/cpdsadapter/DriverAdapterCPDS.java Tue Jun 19 11:21:13 2018 @@ -37,7 +37,9 @@ import javax.naming.spi.ObjectFactory; import javax.sql.ConnectionPoolDataSource; import javax.sql.PooledConnection; -import org.apache.tomcat.dbcp.dbcp2.PoolablePreparedStatement; +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; @@ -45,92 +47,79 @@ import org.apache.tomcat.dbcp.pool2.impl /** * <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. + * 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 + * 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. + * 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. + * 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> * - * @author John D. McNally * @since 2.0 */ -public class DriverAdapterCPDS - implements ConnectionPoolDataSource, Referenceable, Serializable, - ObjectFactory { +public class DriverAdapterCPDS implements ConnectionPoolDataSource, Referenceable, Serializable, ObjectFactory { - private static final long serialVersionUID = -4820523787212147844L; + private static final String KEY_USER = "user"; + private static final String KEY_PASSWORD = "password"; - private static final String GET_CONNECTION_CALLED - = "A PooledConnection was already requested from this source, " + 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."; /** Description */ private String description; - /** Password */ - private String password; + /** Url name */ private String url; + /** User name */ - private String user; + 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 = null; + 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; + 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 = false; + private volatile boolean getConnectionCalled; /** Connection properties passed to JDBC Driver */ - private Properties connectionProperties = null; + private Properties connectionProperties; static { // Attempt to prevent deadlocks - see DBCP - 272 @@ -140,7 +129,7 @@ public class DriverAdapterCPDS /** * Controls access to the underlying connection */ - private boolean accessToUnderlyingConnectionAllowed = false; + private boolean accessToUnderlyingConnectionAllowed; /** * Default no-arg constructor for Serialization @@ -149,8 +138,7 @@ public class DriverAdapterCPDS } /** - * Attempt to establish a database connection using the default - * user and password. + * Attempts to establish a database connection using the default user and password. */ @Override public PooledConnection getPooledConnection() throws SQLException { @@ -159,68 +147,65 @@ public class DriverAdapterCPDS /** * Attempt to establish a database connection. - * @param username name to be used for the connection - * @param pass password to be used fur the 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 username, final String pass) + public PooledConnection getPooledConnection(final String pooledUserName, final String pooledUserPassword) throws SQLException { getConnectionCalled = true; - PooledConnectionImpl pci = null; - // Workaround for buggy WebLogic 5.1 classloader - ignore the - // exception upon first invocation. + PooledConnectionImpl pooledConnection = null; + // Workaround for buggy WebLogic 5.1 classloader - ignore the exception upon first invocation. try { if (connectionProperties != null) { - connectionProperties.put("user", username); - connectionProperties.put("password", pass); - pci = new PooledConnectionImpl(DriverManager.getConnection( - getUrl(), connectionProperties)); + update(connectionProperties, KEY_USER, pooledUserName); + update(connectionProperties, KEY_PASSWORD, pooledUserPassword); + pooledConnection = new PooledConnectionImpl( + DriverManager.getConnection(getUrl(), connectionProperties)); } else { - pci = new PooledConnectionImpl(DriverManager.getConnection( - getUrl(), username, pass)); + pooledConnection = new PooledConnectionImpl( + DriverManager.getConnection(getUrl(), pooledUserName, pooledUserPassword)); } - pci.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed()); - } - catch (final ClassCircularityError e) - { + pooledConnection.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed()); + } catch (final ClassCircularityError e) { if (connectionProperties != null) { - pci = new PooledConnectionImpl(DriverManager.getConnection( - getUrl(), connectionProperties)); + pooledConnection = new PooledConnectionImpl( + DriverManager.getConnection(getUrl(), connectionProperties)); } else { - pci = new PooledConnectionImpl(DriverManager.getConnection( - getUrl(), username, pass)); + pooledConnection = new PooledConnectionImpl( + DriverManager.getConnection(getUrl(), pooledUserName, pooledUserPassword)); } - pci.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed()); + pooledConnection.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed()); } - KeyedObjectPool<PStmtKeyCPDS, PoolablePreparedStatement<PStmtKeyCPDS>> stmtPool = null; + KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> stmtPool = null; if (isPoolPreparedStatements()) { - final GenericKeyedObjectPoolConfig<PoolablePreparedStatement<PStmtKeyCPDS>> config = new GenericKeyedObjectPoolConfig<>(); + final GenericKeyedObjectPoolConfig 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. + 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 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.tomcat.dbcp.pool2.impl.GenericKeyedObjectPool.clearOldest method + } 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<>(pci, config); - pci.setStatementPool(stmtPool); + stmtPool = new GenericKeyedObjectPool<>(pooledConnection, config); + pooledConnection.setStatementPool(stmtPool); } - return pci; + return pooledConnection; } @Override @@ -243,29 +228,21 @@ public class DriverAdapterCPDS ref.add(new StringRefAddr("description", getDescription())); ref.add(new StringRefAddr("driver", getDriver())); - ref.add(new StringRefAddr("loginTimeout", - String.valueOf(getLoginTimeout()))); - ref.add(new StringRefAddr("password", getPassword())); - ref.add(new StringRefAddr("user", getUser())); + 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()))); + 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; } - // ---------------------------------------------------------------------- // ObjectFactory implementation @@ -273,14 +250,13 @@ public class DriverAdapterCPDS * implements 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 { + 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; + final Reference ref = (Reference) refObj; if (ref.getClassName().equals(getClass().getName())) { RefAddr ra = ref.get("description"); if (ra != null && ra.getContent() != null) { @@ -295,19 +271,18 @@ public class DriverAdapterCPDS if (ra != null && ra.getContent() != null) { setUrl(ra.getContent().toString()); } - ra = ref.get("user"); + ra = ref.get(KEY_USER); if (ra != null && ra.getContent() != null) { setUser(ra.getContent().toString()); } - ra = ref.get("password"); + ra = ref.get(KEY_PASSWORD); if (ra != null && ra.getContent() != null) { setPassword(ra.getContent().toString()); } ra = ref.get("poolPreparedStatements"); if (ra != null && ra.getContent() != null) { - setPoolPreparedStatements(Boolean.valueOf( - ra.getContent().toString()).booleanValue()); + setPoolPreparedStatements(Boolean.valueOf(ra.getContent().toString()).booleanValue()); } ra = ref.get("maxIdle"); if (ra != null && ra.getContent() != null) { @@ -316,31 +291,26 @@ public class DriverAdapterCPDS ra = ref.get("timeBetweenEvictionRunsMillis"); if (ra != null && ra.getContent() != null) { - setTimeBetweenEvictionRunsMillis( - Integer.parseInt(ra.getContent().toString())); + setTimeBetweenEvictionRunsMillis(Integer.parseInt(ra.getContent().toString())); } ra = ref.get("numTestsPerEvictionRun"); if (ra != null && ra.getContent() != null) { - setNumTestsPerEvictionRun( - Integer.parseInt(ra.getContent().toString())); + setNumTestsPerEvictionRun(Integer.parseInt(ra.getContent().toString())); } ra = ref.get("minEvictableIdleTimeMillis"); if (ra != null && ra.getContent() != null) { - setMinEvictableIdleTimeMillis( - Integer.parseInt(ra.getContent().toString())); + setMinEvictableIdleTimeMillis(Integer.parseInt(ra.getContent().toString())); } ra = ref.get("maxPreparedStatements"); if (ra != null && ra.getContent() != null) { - setMaxPreparedStatements( - Integer.parseInt(ra.getContent().toString())); + setMaxPreparedStatements(Integer.parseInt(ra.getContent().toString())); } ra = ref.get("accessToUnderlyingConnectionAllowed"); if (ra != null && ra.getContent() != null) { - setAccessToUnderlyingConnectionAllowed( - Boolean.valueOf(ra.getContent().toString()).booleanValue()); + setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(ra.getContent().toString()).booleanValue()); } cpds = this; @@ -350,8 +320,7 @@ public class DriverAdapterCPDS } /** - * Throws an IllegalStateException, if a PooledConnection has already - * been requested. + * Throws an IllegalStateException, if a PooledConnection has already been requested. */ private void assertInitializationAllowed() throws IllegalStateException { if (getConnectionCalled) { @@ -372,35 +341,40 @@ public class DriverAdapterCPDS } /** - * <p>Sets the connection properties passed to the JDBC driver.</p> - * - * <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> + * <p> + * Sets the connection properties passed to the JDBC driver. + * </p> * - * @param props Connection properties to use when creating new connections. - * @throws IllegalStateException if {@link #getPooledConnection()} has been called + * <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.containsKey("user")) { - setUser(connectionProperties.getProperty("user")); - } - if (connectionProperties.containsKey("password")) { - setPassword(connectionProperties.getProperty("password")); + if (connectionProperties != null) { + if (connectionProperties.containsKey(KEY_USER)) { + setUser(connectionProperties.getProperty(KEY_USER)); + } + if (connectionProperties.containsKey(KEY_PASSWORD)) { + setPassword(connectionProperties.getProperty(KEY_PASSWORD)); + } } } /** - * Gets the value of description. This property is here for use by - * the code which will deploy this datasource. It is not used - * internally. + * 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) @@ -410,39 +384,66 @@ public class DriverAdapterCPDS } /** - * Sets the value of description. This property is here for use by - * the code which will deploy this datasource. It is not used - * internally. + * 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. + * @param v + * Value to assign to description. */ - public void setDescription(final String v) { + public void setDescription(final String v) { this.description = v; } /** * Gets the value of password for the default user. + * + * @return value of password. + * @since 2.4.0 + */ + public char[] getPasswordCharArray() { + return userPassword; + } + + /** + * Gets the value of password for the default user. + * * @return value of password. */ public String getPassword() { - return password; + return Utils.toString(userPassword); } /** * Sets the value of password for the default user. - * @param v Value to assign to password. - * @throws IllegalStateException if {@link #getPooledConnection()} has been called + * + * @param userPassword + * Value to assign to password. + * @throws IllegalStateException + * if {@link #getPooledConnection()} has been called */ - public void setPassword(final String v) { + public void setPassword(final char[] userPassword) { assertInitializationAllowed(); - this.password = v; - if (connectionProperties != null) { - connectionProperties.setProperty("password", v); - } + this.userPassword = userPassword; + update(connectionProperties, KEY_PASSWORD, Utils.toString(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); } /** * Gets the value of url used to locate the database for this datasource. + * * @return value of url. */ public String getUrl() { @@ -451,37 +452,43 @@ public class DriverAdapterCPDS /** * 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 - */ + * + * @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; } /** - * Gets the value of default user (login or username). + * Gets the value of default user (login or user name). + * * @return value of user. */ public String getUser() { - return user; + return userName; } /** - * Sets the value of default user (login or username). - * @param v Value to assign to user. - * @throws IllegalStateException if {@link #getPooledConnection()} has been called + * 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.user = v; - if (connectionProperties != null) { - connectionProperties.setProperty("user", v); - } + this.userName = v; + update(connectionProperties, KEY_USER, v); } /** - * Gets the driver classname. + * Gets the driver class name. + * * @return value of driver. */ public String getDriver() { @@ -489,10 +496,15 @@ public class DriverAdapterCPDS } /** - * Sets the driver classname. Setting the driver classname cause the - * driver to be registered with the DriverManager. - * @param v Value to assign to driver. - * @throws IllegalStateException if {@link #getPooledConnection()} has been called + * 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(); @@ -502,8 +514,8 @@ public class DriverAdapterCPDS } /** - * Gets the maximum time in seconds that this data source can wait - * while attempting to connect to a database. NOT USED. + * 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() { @@ -519,8 +531,8 @@ public class DriverAdapterCPDS } /** - * Sets the maximum time in seconds that this data source will wait - * while attempting to connect to a database. NOT USED. + * 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) { @@ -535,13 +547,12 @@ public class DriverAdapterCPDS logWriter = out; } - // ------------------------------------------------------------------ // PreparedStatement pool properties - /** * Flag to toggle the pooling of <code>PreparedStatement</code>s + * * @return value of poolPreparedStatements. */ public boolean isPoolPreparedStatements() { @@ -550,17 +561,21 @@ public class DriverAdapterCPDS /** * Flag to toggle the pooling of <code>PreparedStatement</code>s - * @param v true to pool statements. - * @throws IllegalStateException if {@link #getPooledConnection()} has been called + * + * @param poolPreparedStatements + * true to pool statements. + * @throws IllegalStateException + * if {@link #getPooledConnection()} has been called */ - public void setPoolPreparedStatements(final boolean v) { + public void setPoolPreparedStatements(final boolean poolPreparedStatements) { assertInitializationAllowed(); - this.poolPreparedStatements = v; + this.poolPreparedStatements = poolPreparedStatements; } /** - * Gets the maximum number of statements that can remain idle in the - * pool, without extra ones being released, or negative for no limit. + * 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() { @@ -568,11 +583,13 @@ public class DriverAdapterCPDS } /** - * Gets the maximum number of statements that can remain idle in the - * pool, without extra ones being released, or negative for no limit. + * 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 + * @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(); @@ -580,87 +597,89 @@ public class DriverAdapterCPDS } /** - * 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. + * 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; + return timeBetweenEvictionRunsMillis; } /** - * Sets the number of milliseconds to sleep between runs of the - * idle object evictor thread. - * When non-positive, no idle object evictor thread will be - * run. + * 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 + * @throws IllegalStateException + * if {@link #getPooledConnection()} has been called */ - public void setTimeBetweenEvictionRunsMillis( - final long timeBetweenEvictionRunsMillis) { + public void setTimeBetweenEvictionRunsMillis(final long timeBetweenEvictionRunsMillis) { assertInitializationAllowed(); - _timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; + this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; } /** - * Gets the number of statements to examine during each run of the - * idle object evictor thread (if any). + * Gets the number of statements to examine during each run of the idle object evictor thread (if any.) * - * *see #setNumTestsPerEvictionRun - * *see #setTimeBetweenEvictionRunsMillis + * @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; + return numTestsPerEvictionRun; } /** - * Sets the number of statements to examine during each run of the - * idle object evictor thread (if any). + * 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, <tt>ceil({*link #numIdle})/abs({*link #getNumTestsPerEvictionRun})</tt> - * 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. + * When a negative value is supplied, <tt>ceil({*link #numIdle})/abs({*link #getNumTestsPerEvictionRun})</tt> 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 + * @param numTestsPerEvictionRun + * number of statements to examine per run * @see #getNumTestsPerEvictionRun() * @see #setTimeBetweenEvictionRunsMillis(long) - * @throws IllegalStateException if {@link #getPooledConnection()} has been called + * @throws IllegalStateException + * if {@link #getPooledConnection()} has been called */ public void setNumTestsPerEvictionRun(final int numTestsPerEvictionRun) { assertInitializationAllowed(); - _numTestsPerEvictionRun = numTestsPerEvictionRun; + this.numTestsPerEvictionRun = numTestsPerEvictionRun; } /** - * 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). + * 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 + * @see #setMinEvictableIdleTimeMillis + * @see #setTimeBetweenEvictionRunsMillis + * @return the minimum amount of time a statement may sit idle in the pool. */ public int getMinEvictableIdleTimeMillis() { - return _minEvictableIdleTimeMillis; + return minEvictableIdleTimeMillis; } /** - * 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) + * 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 + * @throws IllegalStateException + * if {@link #getPooledConnection()} has been called */ public void setMinEvictableIdleTimeMillis(final int minEvictableIdleTimeMillis) { assertInitializationAllowed(); - _minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; + this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; } /** @@ -673,11 +692,11 @@ public class DriverAdapterCPDS } /** - * Sets the value of the accessToUnderlyingConnectionAllowed property. - * It controls if the PoolGuard allows access to the underlying connection. - * (Default: false) + * 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. + * @param allow + * Access to the underlying connection is granted when true. */ public synchronized void setAccessToUnderlyingConnectionAllowed(final boolean allow) { this.accessToUnderlyingConnectionAllowed = allow; @@ -688,18 +707,27 @@ public class DriverAdapterCPDS * * @return maxPrepartedStatements value */ - public int getMaxPreparedStatements() - { - return _maxPreparedStatements; + public int getMaxPreparedStatements() { + return maxPreparedStatements; } /** * Sets the maximum number of prepared statements. - * @param maxPreparedStatements the new maximum number of prepared - * statements + * + * @param maxPreparedStatements + * the new maximum number of prepared statements */ - public void setMaxPreparedStatements(final int maxPreparedStatements) - { - _maxPreparedStatements = maxPreparedStatements; + public void setMaxPreparedStatements(final int maxPreparedStatements) { + this.maxPreparedStatements = maxPreparedStatements; + } + + private void update(final Properties properties, final String key, final String value) { + if (properties != null) { + if (value == null) { + properties.remove(key); + } else { + properties.setProperty(key, value); + } + } } } Modified: tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/cpdsadapter/PStmtKeyCPDS.java URL: http://svn.apache.org/viewvc/tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/cpdsadapter/PStmtKeyCPDS.java?rev=1833816&r1=1833815&r2=1833816&view=diff ============================================================================== --- tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/cpdsadapter/PStmtKeyCPDS.java (original) +++ tomcat/tc8.0.x/trunk/java/org/apache/tomcat/dbcp/dbcp2/cpdsadapter/PStmtKeyCPDS.java Tue Jun 19 11:21:13 2018 @@ -16,122 +16,38 @@ */ package org.apache.tomcat.dbcp.dbcp2.cpdsadapter; -import java.util.Arrays; - 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 { - private final Integer _resultSetHoldability; - private final int _columnIndexes[]; - private final String _columnNames[]; - public PStmtKeyCPDS(final String sql) { super(sql); - _resultSetHoldability = null; - _columnIndexes = null; - _columnNames = null; } public PStmtKeyCPDS(final String sql, final int autoGeneratedKeys) { super(sql, null, autoGeneratedKeys); - _resultSetHoldability = null; - _columnIndexes = null; - _columnNames = null; } public PStmtKeyCPDS(final String sql, final int resultSetType, final int resultSetConcurrency) { super(sql, resultSetType, resultSetConcurrency); - _resultSetHoldability = null; - _columnIndexes = null; - _columnNames = null; } public PStmtKeyCPDS(final String sql, final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) { super(sql, resultSetType, resultSetConcurrency); - _resultSetHoldability = Integer.valueOf(resultSetHoldability); - _columnIndexes = null; - _columnNames = null; } public PStmtKeyCPDS(final String sql, final int columnIndexes[]) { - super(sql); - _columnIndexes = Arrays.copyOf(columnIndexes, columnIndexes.length); - _resultSetHoldability = null; - _columnNames = null; + super(sql, null, columnIndexes); } public PStmtKeyCPDS(final String sql, final String columnNames[]) { - super(sql); - _columnNames = Arrays.copyOf(columnNames, columnNames.length); - _resultSetHoldability = null; - _columnIndexes = null; - } - - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final PStmtKeyCPDS other = (PStmtKeyCPDS) obj; - if (!Arrays.equals(_columnIndexes, other._columnIndexes)) { - return false; - } - if (!Arrays.equals(_columnNames, other._columnNames)) { - return false; - } - if (_resultSetHoldability == null) { - if (other._resultSetHoldability != null) { - return false; - } - } else if (!_resultSetHoldability.equals(other._resultSetHoldability)) { - return false; - } - return true; - } - - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + Arrays.hashCode(_columnIndexes); - result = prime * result + Arrays.hashCode(_columnNames); - result = prime * result + (_resultSetHoldability == null ? 0 : _resultSetHoldability.hashCode()); - return result; - } - - - @Override - public String toString() { - final StringBuffer buf = new StringBuffer(); - buf.append("PStmtKey: sql="); - buf.append(getSql()); - buf.append(", catalog="); - buf.append(getCatalog()); - buf.append(", resultSetType="); - buf.append(getResultSetType()); - buf.append(", resultSetConcurrency="); - buf.append(getResultSetConcurrency()); - buf.append(", statementType="); - buf.append(getStmtType()); - buf.append(", resultSetHoldability="); - buf.append(_resultSetHoldability); - buf.append(", columnIndexes="); - buf.append(Arrays.toString(_columnIndexes)); - buf.append(", columnNames="); - buf.append(Arrays.toString(_columnNames)); - return buf.toString(); + super(sql, null, columnNames); } } --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org For additional commands, e-mail: dev-h...@tomcat.apache.org