This is an automated email from the ASF dual-hosted git repository. garydgregory pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-dbcp.git
commit 2da5065952a4477b2f7fba825ab89bc40c255f24 Author: Gary Gregory <[email protected]> AuthorDate: Mon Nov 23 09:45:06 2026 -0500 Preserve login timeouts when deserializing unregistered data sources Share live login timeout configuration only when deserialization reuses a registered data source. Otherwise, retain the serialized local setting, including the distinction between an unset timeout and explicit zero. Add regression coverage for repeated serialization, timeout boundaries, direct and JNDI providers, and registered sources before pool initialization. Extract common test setup and serialization helpers. Complete Javadoc for timeout methods and tests. Add @since 2.15.0 to new public and protected API methods, and update release notes. --- src/changes/changes.xml | 1 + .../commons/dbcp2/DelegatingPreparedStatement.java | 12 +- .../commons/dbcp2/PoolableCallableStatement.java | 7 + .../commons/dbcp2/PoolablePreparedStatement.java | 7 + .../dbcp2/cpdsadapter/DriverAdapterCPDS.java | 36 +++ .../datasources/AbstractConnectionFactory.java | 20 ++ .../dbcp2/datasources/CPDSConnectionFactory.java | 22 +- .../datasources/ConnectionPoolDataSourceUtils.java | 57 +++- .../dbcp2/datasources/InstanceKeyDataSource.java | 48 ++- .../datasources/KeyedCPDSConnectionFactory.java | 17 +- .../dbcp2/datasources/PerUserPoolDataSource.java | 5 + .../dbcp2/datasources/SharedPoolDataSource.java | 5 + .../org/apache/commons/dbcp2/TestJdbcTimeouts.java | 143 +++++++++ .../TestDriverAdapterCPDSReference.java | 45 +++ .../dbcp2/datasources/TestLoginTimeout.java | 340 ++++++++++++++++++++- 15 files changed, 724 insertions(+), 41 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 5575f742..3263088f 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -84,6 +84,7 @@ The <action> type attribute can be add,update,fix,remove. <action type="fix" dev="ggregory" due-to="Gary Gregory">Restore the original query timeout when returning pooled prepared and callable statements, preventing timeout settings from leaking between borrowers.</action> <action type="fix" dev="ggregory" due-to="Gary Gregory">Preserve DriverAdapterCPDS eviction durations through JNDI References, including negative fractional seconds on Java 8, preferring Duration properties and accepting long legacy millisecond values.</action> <action type="fix" dev="ggregory" due-to="Gary Gregory">Apply SharedPoolDataSource and PerUserPoolDataSource login timeouts to every physical connection attempt, restoring the underlying provider's timeout afterwards. Bound waits to configure the provider, and preserve live timeout settings across deserialization.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Preserve local login timeout settings when SharedPoolDataSource and PerUserPoolDataSource are deserialized before configuring a connection provider, including the distinction between an unset timeout and explicit zero.</action> <!-- ADD --> <action type="add" dev="ggregory" due-to="Gary Gregory">Add DriverAdapterCPDS.exportPasswordAsRefAddr to optionally omit the password address from JNDI References. Password export remains enabled by default for compatibility; the setting survives JNDI lookup and Java serialization.</action> <action type="add" dev="ggregory" due-to="Gary Gregory">Add PoolingDriver.Builder and PoolingDriver.builder() to configure delegate access when creating drivers, preserving the existing permissive default.</action> diff --git a/src/main/java/org/apache/commons/dbcp2/DelegatingPreparedStatement.java b/src/main/java/org/apache/commons/dbcp2/DelegatingPreparedStatement.java index caaa72ad..b924c2a7 100644 --- a/src/main/java/org/apache/commons/dbcp2/DelegatingPreparedStatement.java +++ b/src/main/java/org/apache/commons/dbcp2/DelegatingPreparedStatement.java @@ -429,6 +429,7 @@ public class DelegatingPreparedStatement extends DelegatingStatement implements * Sets the delegate, discarding any saved query timeout when the delegate changes. * * @param statement the new delegate. + * @since 2.15.0 */ @Override public void setDelegate(final Statement statement) { @@ -616,7 +617,16 @@ public class DelegatingPreparedStatement extends DelegatingStatement implements } } - /** Caches the original timeout before changing a statement that will be returned to a pool. */ + /** + * Sets the query timeout after caching the original value for restoration when the statement returns to its pool. + * + * <p> + * The original value is read only before the first change and remains cached until the statement returns to its pool or its delegate changes. + * </p> + * + * @param seconds the query timeout in seconds; zero means no timeout. + * @throws SQLException if the statement is closed or reading or changing its timeout fails. + */ void setQueryTimeoutAndCacheOriginal(final int seconds) throws SQLException { checkOpen(); if (originalQueryTimeout == null) { diff --git a/src/main/java/org/apache/commons/dbcp2/PoolableCallableStatement.java b/src/main/java/org/apache/commons/dbcp2/PoolableCallableStatement.java index 9ba77f4b..699c11bd 100644 --- a/src/main/java/org/apache/commons/dbcp2/PoolableCallableStatement.java +++ b/src/main/java/org/apache/commons/dbcp2/PoolableCallableStatement.java @@ -108,6 +108,13 @@ public class PoolableCallableStatement extends DelegatingCallableStatement { prepareToReturn(); } + /** + * Sets the query timeout while retaining the original value for restoration when this statement returns to its pool. + * + * @param seconds the query timeout in seconds; zero means no timeout. + * @throws SQLException if the statement is closed, the timeout is negative, or reading or changing the timeout fails. + * @since 2.15.0 + */ @Override public void setQueryTimeout(final int seconds) throws SQLException { setQueryTimeoutAndCacheOriginal(seconds); diff --git a/src/main/java/org/apache/commons/dbcp2/PoolablePreparedStatement.java b/src/main/java/org/apache/commons/dbcp2/PoolablePreparedStatement.java index 8752e3aa..9d5aad1c 100644 --- a/src/main/java/org/apache/commons/dbcp2/PoolablePreparedStatement.java +++ b/src/main/java/org/apache/commons/dbcp2/PoolablePreparedStatement.java @@ -132,6 +132,13 @@ public class PoolablePreparedStatement<K> extends DelegatingPreparedStatement { prepareToReturn(); } + /** + * Sets the query timeout while retaining the original value for restoration when this statement returns to its pool. + * + * @param seconds the query timeout in seconds; zero means no timeout. + * @throws SQLException if the statement is closed, the timeout is negative, or reading or changing the timeout fails. + * @since 2.15.0 + */ @Override public void setQueryTimeout(final int seconds) throws SQLException { setQueryTimeoutAndCacheOriginal(seconds); diff --git a/src/main/java/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS.java b/src/main/java/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS.java index 4d04a618..1ed087e2 100644 --- a/src/main/java/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS.java +++ b/src/main/java/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS.java @@ -184,6 +184,19 @@ public class DriverAdapterCPDS implements ConnectionPoolDataSource, Referenceabl public DriverAdapterCPDS() { } + /** + * Adds a duration property and, when representable, its legacy millisecond property to a JNDI Reference. + * + * <p> + * The legacy property is omitted when converting the duration to milliseconds would overflow a {@code long}. + * </p> + * + * @param reference the Reference to update. + * @param durationKey the address type for the ISO-8601 duration. + * @param millisKey the address type for the legacy millisecond value. + * @param duration the duration to export, not null. + * @throws NullPointerException if reference or duration is null. + */ private void addDurationReference(final Reference reference, final String durationKey, final String millisKey, final Duration duration) { reference.add(new StringRefAddr(durationKey, duration.toString())); try { @@ -251,6 +264,16 @@ public class DriverAdapterCPDS implements ConnectionPoolDataSource, Referenceabl return durationBetweenEvictionRuns; } + /** + * Gets a duration from a JNDI Reference, preferring the ISO-8601 property over the legacy millisecond property. + * + * @param reference the Reference to read. + * @param durationKey the address type for the ISO-8601 duration. + * @param millisKey the address type for the legacy millisecond value. + * @return the configured duration, or {@code null} if both properties are absent or empty. + * @throws java.time.format.DateTimeParseException if the nonempty ISO-8601 property is invalid. + * @throws NumberFormatException if the selected legacy property is not a valid long integer. + */ private Duration getDuration(final Reference reference, final String durationKey, final String millisKey) { final RefAddr duration = reference.get(durationKey); if (isNotEmpty(duration)) { @@ -631,6 +654,19 @@ public class DriverAdapterCPDS implements ConnectionPoolDataSource, Referenceabl return poolPreparedStatements; } + /** + * Parses a duration without losing the sign of negative fractional seconds on Java 8. + * + * <p> + * A negative-zero seconds component is temporarily changed to negative one before parsing. The result is adjusted by one second, respecting any leading + * sign for the whole duration. + * </p> + * + * @param text the duration text, not null. + * @return the parsed duration. + * @throws java.time.format.DateTimeParseException if the text is invalid or the duration exceeds the supported range. + * @throws NullPointerException if text is null. + */ private Duration parseDuration(final String text) { final Matcher matcher = NEGATIVE_ZERO_SECONDS_PATTERN.matcher(text); if (matcher.find()) { diff --git a/src/main/java/org/apache/commons/dbcp2/datasources/AbstractConnectionFactory.java b/src/main/java/org/apache/commons/dbcp2/datasources/AbstractConnectionFactory.java index f1ad111e..061aaadc 100644 --- a/src/main/java/org/apache/commons/dbcp2/datasources/AbstractConnectionFactory.java +++ b/src/main/java/org/apache/commons/dbcp2/datasources/AbstractConnectionFactory.java @@ -57,6 +57,17 @@ class AbstractConnectionFactory { protected final String validationQuery; protected final Duration validationQueryTimeoutDuration; + /** + * Constructs a connection factory with validation, lifetime, and live login timeout settings. + * + * @param cpds the provider from which to obtain pooled connections. + * @param validationQuery the validation query, or {@code null} to use {@link Connection#isValid(int)}. + * @param validationQueryTimeoutDuration the timeout for connection validation. + * @param rollbackAfterValidation whether to roll back after executing the validation query. + * @param maxConnDuration the maximum connection lifetime, not null; zero or a negative duration disables the limit. + * @param loginTimeoutSupplier the supplier of the current login timeout, not null; a supplied {@code null} preserves the provider setting. + * @throws NullPointerException if maxConnDuration or loginTimeoutSupplier is null. + */ AbstractConnectionFactory(final ConnectionPoolDataSource cpds, final String validationQuery, final Duration validationQueryTimeoutDuration, final boolean rollbackAfterValidation, final Duration maxConnDuration, Supplier<Duration> loginTimeoutSupplier) { this.cpds = cpds; @@ -67,6 +78,15 @@ class AbstractConnectionFactory { this.loginTimeoutSupplier = Objects.requireNonNull(loginTimeoutSupplier, "loginTimeoutSupplier"); } + /** + * Gets a pooled connection using the supplied credentials and the current login timeout. + * + * @param userPassKey the credentials, not null; a null user name selects the provider's default credentials. + * @return the pooled connection returned by the provider. + * @throws SQLException if provider access fails, waiting for the provider lock times out, or the wait is interrupted. + * @throws NullPointerException if userPassKey is null. + * @since 2.15.0 + */ protected PooledConnection getPooledConnection(final UserPassKey userPassKey) throws SQLException { return ConnectionPoolDataSourceUtils.getPooledConnection(cpds, userPassKey.getUserName(), userPassKey.getPassword(), loginTimeoutSupplier.get()); } diff --git a/src/main/java/org/apache/commons/dbcp2/datasources/CPDSConnectionFactory.java b/src/main/java/org/apache/commons/dbcp2/datasources/CPDSConnectionFactory.java index b33a72a0..49c7de32 100644 --- a/src/main/java/org/apache/commons/dbcp2/datasources/CPDSConnectionFactory.java +++ b/src/main/java/org/apache/commons/dbcp2/datasources/CPDSConnectionFactory.java @@ -26,7 +26,6 @@ import javax.sql.ConnectionEventListener; import javax.sql.ConnectionPoolDataSource; import javax.sql.PooledConnection; -import org.apache.commons.dbcp2.PoolableConnectionFactory; import org.apache.commons.pool2.ObjectPool; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.PooledObjectFactory; @@ -46,18 +45,17 @@ final class CPDSConnectionFactory extends AbstractConnectionFactory private UserPassKey userPassKey; /** - * Constructs a new {@link PoolableConnectionFactory}. + * Constructs a factory for pooled connections using one set of credentials. * - * @param cpds The ConnectionPoolDataSource from which to obtain PooledConnection's - * @param validationQuery A query to use to {@link #validateObject validate} {@link Connection}s. Should return at least one row. May be - * {@code null} in which case {@link Connection#isValid(int)} will be used to validate connections. - * @param validationQueryTimeoutDuration Timeout Duration before validation fails. - * @param rollbackAfterValidation whether a rollback should be issued after {@link #validateObject validating} {@link Connection}s. - * @param userName The user name to use to create connections. - * @param userPassword The password to use to create connections. - * @param maxConnDuration The maximum lifetime of a connection after which the connection will always fail activation, passivation and - * validation. A value of zero or less indicates an infinite lifetime. - * @param loginTimeoutSupplier Supplies the login timeout, may not be null. + * @param cpds the provider from which to obtain pooled connections. + * @param validationQuery the validation query, or {@code null} to use {@link Connection#isValid(int)}. + * @param validationQueryTimeoutDuration the timeout for connection validation. + * @param rollbackAfterValidation whether to roll back after executing the validation query. + * @param userName the user name, or {@code null} to use the provider's default credentials. + * @param userPassword the password for the supplied user name. + * @param maxConnDuration the maximum connection lifetime, not null; zero or a negative duration disables the limit. + * @param loginTimeoutSupplier the supplier of the current login timeout, not null; a supplied {@code null} preserves the provider setting. + * @throws NullPointerException if maxConnDuration or loginTimeoutSupplier is null. */ CPDSConnectionFactory(final ConnectionPoolDataSource cpds, final String validationQuery, final Duration validationQueryTimeoutDuration, final boolean rollbackAfterValidation, final String userName, final char[] userPassword, final Duration maxConnDuration, diff --git a/src/main/java/org/apache/commons/dbcp2/datasources/ConnectionPoolDataSourceUtils.java b/src/main/java/org/apache/commons/dbcp2/datasources/ConnectionPoolDataSourceUtils.java index 86169426..9a97800c 100644 --- a/src/main/java/org/apache/commons/dbcp2/datasources/ConnectionPoolDataSourceUtils.java +++ b/src/main/java/org/apache/commons/dbcp2/datasources/ConnectionPoolDataSourceUtils.java @@ -42,11 +42,22 @@ final class ConnectionPoolDataSourceUtils { private static final class ProviderReference extends WeakReference<ConnectionPoolDataSource> { private final int hashCode; + /** + * Constructs a weak provider reference with a stable identity hash code. + * + * @param provider the provider to track by identity. + */ ProviderReference(final ConnectionPoolDataSource provider) { super(provider, STALE_PROVIDERS); hashCode = System.identityHashCode(provider); } + /** + * Tests whether this reference or its live provider is identical to that of another reference. + * + * @param obj the object to compare with this reference. + * @return true if obj is this reference or another reference to the same live provider. + */ @Override public boolean equals(final Object obj) { if (this == obj) { @@ -56,6 +67,11 @@ final class ConnectionPoolDataSourceUtils { return provider != null && obj instanceof ProviderReference && provider == ((ProviderReference) obj).get(); } + /** + * Gets the provider identity hash code captured when this reference was created. + * + * @return the cached identity hash code, even after the provider is reclaimed. + */ @Override public int hashCode() { return hashCode; @@ -67,13 +83,39 @@ final class ConnectionPoolDataSourceUtils { /** Neither the weak keys nor the lock values retain providers after their pools are closed. */ private static final Map<ProviderReference, ReentrantReadWriteLock> LOCKS = new HashMap<>(); + /** + * Opens a pooled connection using explicit credentials or the provider's default credentials. + * + * @param cpds the provider from which to obtain a pooled connection. + * @param userName the user name, or {@code null} to use the provider's default credentials. + * @param password the password, ignored when userName is null. + * @return the pooled connection returned by the provider. + * @throws SQLException if the provider cannot create the connection. + */ private static PooledConnection connect(final ConnectionPoolDataSource cpds, final String userName, final String password) throws SQLException { return userName == null ? cpds.getPooledConnection() : cpds.getPooledConnection(userName, password); } /** - * Opens a physical connection with an optional login timeout, restoring the provider's setting afterwards. - * Timeout overrides exclude other connection attempts through these pools. Attempts without an override remain concurrent. + * Gets a pooled connection using an optional temporary provider login timeout. + * + * <p> + * Timeout overrides exclude other connection attempts through these pools. Attempts without an override may run concurrently. A positive override also + * bounds the provider lock wait in JDBC seconds; the provider enforces the connection timeout. + * </p> + * + * <p> + * After changing the timeout, this method attempts to restore its previous value. Restoration failures are suppressed on an existing failure; otherwise, + * the acquired connection is closed and the restoration failure is thrown. + * </p> + * + * @param cpds the provider from which to obtain a pooled connection. + * @param userName the user name, or {@code null} to use the provider's default credentials. + * @param password the password, ignored when userName is null. + * @param loginTimeout the timeout override, or {@code null} to retain the provider setting. + * @return the pooled connection returned by the provider. + * @throws SQLException if accessing or restoring the provider fails, the provider lock wait expires, or waiting is interrupted. + * @throws NullPointerException if cpds is null. */ static PooledConnection getPooledConnection(final ConnectionPoolDataSource cpds, final String userName, final String password, final Duration loginTimeout) throws SQLException { @@ -133,6 +175,14 @@ final class ConnectionPoolDataSourceUtils { } } + /** + * Acquires a provider lock interruptibly, using a bounded wait for positive timeouts. + * + * @param lock the provider lock to acquire. + * @param timeout the wait limit, or {@code null}, zero, or a negative value for an unbounded wait. + * @throws SQLException if the wait is interrupted; the thread's interrupted status is preserved. + * @throws SQLTimeoutException if the bounded lock wait expires. + */ private static void lock(final Lock lock, final Duration timeout) throws SQLException { try { if (timeout != null && !timeout.isNegative() && !timeout.isZero()) { @@ -148,6 +198,9 @@ final class ConnectionPoolDataSourceUtils { } } + /** + * Prevents instantiation of this utility class. + */ private ConnectionPoolDataSourceUtils() { // Not instantiable. } diff --git a/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java b/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java index f0a5ccce..200ddea0 100644 --- a/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java +++ b/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java @@ -106,7 +106,9 @@ public abstract class InstanceKeyDataSource implements DataSource, Referenceable /** Login timeout, or null to retain the provider's configuration. */ private volatile Duration loginTimeoutDuration; - /** Original datasource whose pool and live login timeout are shared after deserialization. */ + /** + * Registered data source supplying the live login timeout after deserialization, or null to use the local setting. + */ private transient InstanceKeyDataSource loginTimeoutSource; /** Log stream */ @@ -319,7 +321,16 @@ public abstract class InstanceKeyDataSource implements DataSource, Referenceable */ protected abstract PooledConnectionManager getConnectionManager(UserPassKey upkey); - /** Gets the optional timeout used for physical connection attempts. */ + /** + * Gets the optional timeout used for physical connection attempts. + * + * <p> + * Deserialized instances that reuse a registered data source read its live configuration. Otherwise, the local setting is used, including a timeout + * serialized before a provider or JNDI data source name has been configured. An unset timeout remains distinct from an explicitly configured zero. + * </p> + * + * @return the local or shared timeout, or {@code null} to leave the provider's configured timeout unchanged. + */ Duration getConfiguredLoginTimeout() { return loginTimeoutSource == null ? loginTimeoutDuration : loginTimeoutSource.getConfiguredLoginTimeout(); } @@ -608,9 +619,14 @@ public abstract class InstanceKeyDataSource implements DataSource, Referenceable } /** - * Gets the value of loginTimeout. + * Gets the configured login timeout, or zero if no override has been configured. + * + * <p> + * Both an unset timeout and an explicitly configured zero are reported as {@link Duration#ZERO}. An unset timeout leaves the provider's configuration + * unchanged, while an explicit zero is passed to the provider. Deserialized instances that reuse a registered data source report its live setting. + * </p> * - * @return value of loginTimeout. + * @return the configured timeout, or {@link Duration#ZERO} if no override has been configured. * @since 2.10.0 */ public Duration getLoginTimeoutDuration() { @@ -1130,8 +1146,13 @@ public abstract class InstanceKeyDataSource implements DataSource, Referenceable /** * Sets the timeout applied to the underlying ConnectionPoolDataSource for each physical connection attempt, * including connections created after pool initialization. The provider's previous timeout is restored afterwards. - * Until this method is called, the provider's configured timeout is used unchanged. Deserialized wrappers sharing - * the same pool also share this live configuration. + * Until an override is configured, the provider's configured timeout is used unchanged. + * + * <p> + * Deserialized instances that reuse a registered data source share its live login timeout configuration, even before the pool is initialized. + * Instances serialized before a provider or JNDI data source name has been configured retain their own serialized timeout setting. + * </p> + * * <p> * Positive durations use whole seconds, with a minimum of one second and a maximum of {@link Integer#MAX_VALUE}. * Zero uses the provider's default login timeout behavior. Enforcement depends on the provider; this setting does @@ -1158,7 +1179,7 @@ public abstract class InstanceKeyDataSource implements DataSource, Referenceable } /** - * Sets the value of loginTimeout. + * Sets the login timeout in seconds. * * @param loginTimeout a nonnegative timeout in seconds. * @throws IllegalArgumentException if loginTimeout is negative. @@ -1168,9 +1189,18 @@ public abstract class InstanceKeyDataSource implements DataSource, Referenceable setLoginTimeout(Duration.ofSeconds(loginTimeout)); } - /** Shares the live login timeout configuration along with the pool during deserialization. */ + /** + * Sets the source of the live login timeout configuration when deserialization reuses a registered data source. + * + * <p> + * Without an instance key, the factory creates a new data source instead of locating an existing one. In that case, the supplied source is ignored + * and this instance retains its own deserialized timeout setting. + * </p> + * + * @param source the registered data source whose configuration is shared, or {@code null} to use this instance's setting. + */ final void setLoginTimeoutSource(final InstanceKeyDataSource source) { - loginTimeoutSource = source; + loginTimeoutSource = instanceKey == null ? null : source; } /** diff --git a/src/main/java/org/apache/commons/dbcp2/datasources/KeyedCPDSConnectionFactory.java b/src/main/java/org/apache/commons/dbcp2/datasources/KeyedCPDSConnectionFactory.java index 2c72c00c..cba164b1 100644 --- a/src/main/java/org/apache/commons/dbcp2/datasources/KeyedCPDSConnectionFactory.java +++ b/src/main/java/org/apache/commons/dbcp2/datasources/KeyedCPDSConnectionFactory.java @@ -44,16 +44,15 @@ final class KeyedCPDSConnectionFactory extends AbstractConnectionFactory private KeyedObjectPool<UserPassKey, PooledConnectionAndInfo> pool; /** - * Constructs a new {@code KeyedCPDSConnectionFactory}. + * Constructs a factory for pooled connections keyed by user credentials. * - * @param cpds The ConnectionPoolDataSource from which to obtain PooledConnections - * @param validationQuery A query to use to {@link #validateObject validate} {@link Connection}s. Should return at least one row. May be - * {@code null} in which case3 {@link Connection#isValid(int)} will be used to validate connections. - * @param validationQueryTimeoutDuration The Duration to allow for the validation query to complete - * @param rollbackAfterValidation Whether a rollback should be issued after {@link #validateObject validating} {@link Connection}s. - * @param maxConnDuration The maximum lifetime of a connection after which the connection will always fail activation, passivation and - * validation. A value of zero or less indicates an infinite lifetime. - * @param loginTimeoutSupplier Supplies the login timeout, may not be null. + * @param cpds the provider from which to obtain pooled connections. + * @param validationQuery the validation query, or {@code null} to use {@link Connection#isValid(int)}. + * @param validationQueryTimeoutDuration the timeout for connection validation. + * @param rollbackAfterValidation whether to roll back after executing the validation query. + * @param maxConnDuration the maximum connection lifetime, not null; zero or a negative duration disables the limit. + * @param loginTimeoutSupplier the supplier of the current login timeout, not null; a supplied {@code null} preserves the provider setting. + * @throws NullPointerException if maxConnDuration or loginTimeoutSupplier is null. */ KeyedCPDSConnectionFactory(final ConnectionPoolDataSource cpds, final String validationQuery, final Duration validationQueryTimeoutDuration, final boolean rollbackAfterValidation, final Duration maxConnDuration, Supplier<Duration> loginTimeoutSupplier) { diff --git a/src/main/java/org/apache/commons/dbcp2/datasources/PerUserPoolDataSource.java b/src/main/java/org/apache/commons/dbcp2/datasources/PerUserPoolDataSource.java index efea42af..5ba80142 100644 --- a/src/main/java/org/apache/commons/dbcp2/datasources/PerUserPoolDataSource.java +++ b/src/main/java/org/apache/commons/dbcp2/datasources/PerUserPoolDataSource.java @@ -666,6 +666,11 @@ public class PerUserPoolDataSource extends InstanceKeyDataSource { /** * Deserializes an instance from an ObjectInputStream. * + * <p> + * When the registration key resolves to an existing data source, its pool managers and live login timeout configuration are reused. An instance serialized + * without a key retains its own login timeout setting. + * </p> + * * @param in The source ObjectInputStream. * @throws IOException Any of the usual Input/Output related exceptions. * @throws ClassNotFoundException A class of a serialized object cannot be found. diff --git a/src/main/java/org/apache/commons/dbcp2/datasources/SharedPoolDataSource.java b/src/main/java/org/apache/commons/dbcp2/datasources/SharedPoolDataSource.java index aff6cbdc..29f318c6 100644 --- a/src/main/java/org/apache/commons/dbcp2/datasources/SharedPoolDataSource.java +++ b/src/main/java/org/apache/commons/dbcp2/datasources/SharedPoolDataSource.java @@ -153,6 +153,11 @@ public class SharedPoolDataSource extends InstanceKeyDataSource { /** * Deserializes an instance from an ObjectInputStream. * + * <p> + * When the registration key resolves to an existing data source, its pool and live login timeout configuration are reused. An instance serialized + * without a key retains its own login timeout setting. + * </p> + * * @param in The source ObjectInputStream. * @throws IOException Any of the usual Input/Output related exceptions. * @throws ClassNotFoundException A class of a serialized object cannot be found. diff --git a/src/test/java/org/apache/commons/dbcp2/TestJdbcTimeouts.java b/src/test/java/org/apache/commons/dbcp2/TestJdbcTimeouts.java index c9d7358a..9c3ec92d 100644 --- a/src/test/java/org/apache/commons/dbcp2/TestJdbcTimeouts.java +++ b/src/test/java/org/apache/commons/dbcp2/TestJdbcTimeouts.java @@ -54,6 +54,15 @@ import org.junit.jupiter.params.provider.ValueSource; /** Tests JDBC timeout conversion and statement timeout isolation. */ class TestJdbcTimeouts { + /** + * Creates a statement using one of the JDBC statement creation overloads. + * + * @param connection the connection that creates the statement. + * @param variant the creation overload index, from 0 through 11. + * @return the created statement. + * @throws SQLException if statement creation fails. + * @throws IllegalArgumentException if variant is not a supported overload index. + */ private static Statement createStatement(final Connection connection, final int variant) throws SQLException { switch (variant) { case 0: @@ -85,6 +94,13 @@ class TestJdbcTimeouts { } } + /** + * Creates a callable statement test double backed by a mutable query timeout. + * + * @param timeout the value read and updated by the timeout accessors. + * @return the statement test double. + * @throws SQLException if configuring the statement test double fails. + */ private static CallableStatement mockStatement(final AtomicInteger timeout) throws SQLException { final CallableStatement statement = mock(CallableStatement.class); when(statement.getQueryTimeout()).thenAnswer(invocation -> timeout.get()); @@ -95,6 +111,12 @@ class TestJdbcTimeouts { return statement; } + /** + * Creates a data source with statement pooling and the supplied default query timeout. + * + * @param defaultTimeout the default query timeout, or {@code null} to retain the driver default. + * @return the configured data source. + */ private static BasicDataSource newDataSource(final Duration defaultTimeout) { final BasicDataSource source = new BasicDataSource(); source.setDriverClassName(TesterDriver.class.getName()); @@ -107,24 +129,49 @@ class TestJdbcTimeouts { return source; } + /** + * Supplies statement types and timeout changes for delegate replacement tests. + * + * @return callable-statement and timeout-change flag combinations. + */ static Stream<Arguments> changedDelegates() { return Stream.of(false, true).flatMap(callable -> Stream.of(false, true).map(changeTimeout -> Arguments.of(callable, changeTimeout))); } + /** + * Supplies statement types and failure modes for timeout setter tests. + * + * @return callable-statement and unchecked-failure flag combinations. + */ static Stream<Arguments> failedTimeoutSetters() { return Stream.of(false, true).flatMap(callable -> Stream.of(false, true).map(unchecked -> Arguments.of(callable, unchecked))); } + /** + * Supplies statement types and default query timeouts for pooled statement tests. + * + * @return statement type and default timeout combinations, including an unset timeout. + */ static Stream<Arguments> pooledTimeouts() { return Stream.of(false, true).flatMap(callable -> Stream.of(null, Duration.ZERO, Duration.ofMillis(100), Duration.ofSeconds(5)) .map(timeout -> Arguments.of(callable, timeout))); } + /** + * Supplies timeout conversion cases for every statement creation overload. + * + * @return creation overloads, durations, and their expected JDBC timeout values. + */ static Stream<Arguments> statementTimeouts() { return IntStream.range(0, 12).boxed().flatMap(variant -> timeouts().map(argument -> Arguments.of(variant, argument.get()[0], argument.get()[1]))); } + /** + * Supplies duration boundary cases and their expected JDBC timeout values. + * + * @return negative, zero, fractional, and oversized duration conversion cases. + */ static Stream<Arguments> timeouts() { return Stream.of( Arguments.of(Duration.ofSeconds(Long.MIN_VALUE), Integer.MIN_VALUE), @@ -146,6 +193,13 @@ class TestJdbcTimeouts { Arguments.of(Duration.ofSeconds(Long.MAX_VALUE, 999_999_999), Integer.MAX_VALUE)); } + /** + * Tests that pooled statement query timeouts are restored between borrowers. + * + * @param callable whether to exercise callable statements instead of prepared statements. + * @param defaultTimeout the configured default query timeout, or {@code null} for the driver default. + * @throws Exception if setting up, using, or closing the test resources fails. + */ @ParameterizedTest @MethodSource("pooledTimeouts") void testBasicDataSourceRestoresTimeoutBetweenBorrowers(final boolean callable, final Duration defaultTimeout) throws Exception { @@ -162,6 +216,12 @@ class TestJdbcTimeouts { } } + /** + * Tests that DriverAdapterCPDS restores query timeouts between statement borrowers. + * + * @param callable whether to exercise callable statements instead of prepared statements. + * @throws Exception if setting up, using, or closing the test resources fails. + */ @ParameterizedTest @ValueSource(booleans = {false, true}) void testCpdsAdapterRestoresTimeout(final boolean callable) throws Exception { @@ -183,6 +243,14 @@ class TestJdbcTimeouts { } } + /** + * Tests timeout conversion, negative timeout rejection, and cleanup for each statement creation overload. + * + * @param variant the statement creation overload index, from 0 through 11. + * @param timeout the duration under test. + * @param expected the expected timeout passed to JDBC, in seconds. + * @throws SQLException if JDBC setup, an operation, or cleanup unexpectedly fails. + */ @ParameterizedTest @MethodSource("statementTimeouts") void testDefaultQueryTimeout(final int variant, final Duration timeout, final int expected) throws SQLException { @@ -211,6 +279,11 @@ class TestJdbcTimeouts { } } + /** + * Tests that a matching query timeout avoids a redundant setter call. + * + * @throws SQLException if JDBC setup, an operation, or cleanup unexpectedly fails. + */ @Test void testDefaultQueryTimeoutAvoidsRedundantSetter() throws SQLException { final Connection raw = mock(Connection.class); @@ -225,6 +298,11 @@ class TestJdbcTimeouts { } } + /** + * Tests that a timeout initialization failure retains a subsequent statement close failure. + * + * @throws SQLException if JDBC setup, an operation, or cleanup unexpectedly fails. + */ @Test void testDefaultQueryTimeoutPreservesInitializationAndCloseFailures() throws SQLException { final Connection raw = mock(Connection.class); @@ -241,6 +319,13 @@ class TestJdbcTimeouts { } } + /** + * Tests direct connection validation timeout conversion and preservation of driver exceptions. + * + * @param timeout the duration under test. + * @param expected the expected timeout passed to JDBC, in seconds. + * @throws SQLException if JDBC setup, an operation, or cleanup unexpectedly fails. + */ @ParameterizedTest @MethodSource("timeouts") void testIsValid(final Duration timeout, final int expected) throws SQLException { @@ -261,6 +346,11 @@ class TestJdbcTimeouts { } } + /** + * Tests that validating a closed wrapper does not call the driver. + * + * @throws SQLException if JDBC setup, an operation, or cleanup unexpectedly fails. + */ @Test void testIsValidClosedDoesNotCallDriver() throws SQLException { final Connection raw = mock(Connection.class); @@ -271,6 +361,12 @@ class TestJdbcTimeouts { } } + /** + * Tests that a statement is discarded when its original query timeout cannot be restored. + * + * @param callable whether to exercise callable statements instead of prepared statements. + * @throws Exception if setting up, using, or closing the test resources fails. + */ @ParameterizedTest @ValueSource(booleans = {false, true}) void testPoolDiscardsStatementWhenTimeoutResetFails(final boolean callable) throws Exception { @@ -291,17 +387,32 @@ class TestJdbcTimeouts { } } + /** + * Tests duration conversion to bounded JDBC timeout seconds. + * + * @param timeout the duration under test. + * @param expected the expected timeout passed to JDBC, in seconds. + */ @ParameterizedTest @MethodSource("timeouts") void testToJdbcSeconds(final Duration timeout, final int expected) { assertEquals(expected, Utils.toJdbcSeconds(timeout)); } + /** + * Tests that JDBC timeout conversion rejects a null duration. + */ @Test void testToJdbcSecondsNull() { assertThrows(NullPointerException.class, () -> Utils.toJdbcSeconds(null)); } + /** + * Tests that closing a connection restores the timeout of a statement left open by its borrower. + * + * @param callable whether to exercise callable statements instead of prepared statements. + * @throws Exception if setting up, using, or closing the test resources fails. + */ @ParameterizedTest @ValueSource(booleans = {false, true}) void testConnectionCloseRestoresUnclosedStatementTimeout(final boolean callable) throws Exception { @@ -317,6 +428,12 @@ class TestJdbcTimeouts { } } + /** + * Tests that an unchanged pooled statement does not access the driver query timeout. + * + * @param callable whether to exercise callable statements instead of prepared statements. + * @throws Exception if setting up, using, or closing the test resources fails. + */ @ParameterizedTest @ValueSource(booleans = {false, true}) void testUntouchedPooledStatementDoesNotReadOrWriteTimeout(final boolean callable) throws Exception { @@ -337,6 +454,12 @@ class TestJdbcTimeouts { } } + /** + * Tests that setting a nonpooled statement timeout does not require driver support for reading it. + * + * @param callable whether to exercise callable statements instead of prepared statements. + * @throws SQLException if JDBC setup, an operation, or cleanup unexpectedly fails. + */ @ParameterizedTest @ValueSource(booleans = {false, true}) void testNonPooledQueryTimeoutDoesNotRequireGetter(final boolean callable) throws SQLException { @@ -349,6 +472,13 @@ class TestJdbcTimeouts { } } + /** + * Tests restoration after a driver changes the timeout and then throws from the setter. + * + * @param callable whether to exercise callable statements instead of prepared statements. + * @param unchecked whether the timeout setter throws an unchecked exception. + * @throws Exception if setting up, using, or closing the test resources fails. + */ @ParameterizedTest @MethodSource("failedTimeoutSetters") void testPooledTimeoutRestoredAfterSetterMutatesAndThrows(final boolean callable, final boolean unchecked) throws Exception { @@ -383,6 +513,13 @@ class TestJdbcTimeouts { } } + /** + * Tests that timeout restoration uses the replacement delegate's original value. + * + * @param callable whether to exercise callable statements instead of prepared statements. + * @param changeTimeout whether to change the replacement delegate's timeout before returning the statement. + * @throws Exception if setting up, using, or closing the test resources fails. + */ @ParameterizedTest @MethodSource("changedDelegates") void testPooledTimeoutFollowsReplacementDelegate(final boolean callable, final boolean changeTimeout) throws Exception { @@ -413,6 +550,12 @@ class TestJdbcTimeouts { } } + /** + * Tests that reassigning the same delegate retains the saved original timeout. + * + * @param callable whether to exercise callable statements instead of prepared statements. + * @throws Exception if setting up, using, or closing the test resources fails. + */ @ParameterizedTest @ValueSource(booleans = {false, true}) void testPooledTimeoutPreservedWhenReassigningSameDelegate(final boolean callable) throws Exception { diff --git a/src/test/java/org/apache/commons/dbcp2/cpdsadapter/TestDriverAdapterCPDSReference.java b/src/test/java/org/apache/commons/dbcp2/cpdsadapter/TestDriverAdapterCPDSReference.java index d7c30596..8621a207 100644 --- a/src/test/java/org/apache/commons/dbcp2/cpdsadapter/TestDriverAdapterCPDSReference.java +++ b/src/test/java/org/apache/commons/dbcp2/cpdsadapter/TestDriverAdapterCPDSReference.java @@ -366,6 +366,11 @@ class TestDriverAdapterCPDSReference { assertCanConnect(restored); } + /** + * Supplies duration and property combinations for JNDI round-trip tests. + * + * @return duration boundaries with and without legacy millisecond properties. + */ static Stream<Arguments> durationReferences() { return Stream.concat(Stream.of(Duration.ZERO, Duration.ofNanos(1), Duration.ofMillis(1_901), Duration.ofDays(30), Duration.ofMillis(Long.MIN_VALUE), Duration.ofMillis(Long.MAX_VALUE), @@ -376,6 +381,11 @@ class TestDriverAdapterCPDSReference { .flatMap(duration -> Stream.of(false, true).map(modernOnly -> Arguments.of(duration, modernOnly))); } + /** + * Supplies JNDI duration strings with independently constructed expected values. + * + * @return duration text and value pairs covering signs, fractions, and range boundaries. + */ static Stream<Arguments> durationReferenceStrings() { return Stream.of( Arguments.of("PT-0.000000001S", Duration.ofNanos(-1)), @@ -407,6 +417,13 @@ class TestDriverAdapterCPDSReference { Arguments.of("PT9223372036854775807.999999999S", Duration.ofSeconds(Long.MAX_VALUE, 999_999_999))); } + /** + * Tests that JNDI References preserve eviction durations through reconstruction. + * + * @param duration the duration under test. + * @param modernOnly whether to omit the legacy millisecond properties. + * @throws Exception if setting up, using, or closing the test resources fails. + */ @ParameterizedTest @MethodSource("durationReferences") void testDurationReferenceRoundTrip(final Duration duration, final boolean modernOnly) throws Exception { @@ -423,6 +440,13 @@ class TestDriverAdapterCPDSReference { assertEquals(duration, restored.getMinEvictableIdleDuration()); } + /** + * Tests duration parsing and precedence over legacy JNDI millisecond properties. + * + * @param text the duration text under test. + * @param expected the duration represented by the supplied text. + * @throws Exception if setting up, using, or closing the test resources fails. + */ @ParameterizedTest @MethodSource("durationReferenceStrings") void testDurationReferenceStrings(final String text, final Duration expected) throws Exception { @@ -436,6 +460,11 @@ class TestDriverAdapterCPDSReference { assertEquals(expected, restored.getMinEvictableIdleDuration()); } + /** + * Tests that malformed or overflowing duration properties fail instead of falling back to legacy values. + * + * @param text the duration text under test. + */ @ParameterizedTest @ValueSource(strings = {"PT-0.1234567890S", "PT--0.1S", "PT-0.-1S", "P-0.1S", "PT-0.1Sx", " PT-0.1S", "PT-0.1S\n", "PT1M-0.1S-0.1S", "PT-0.1", "PT-0,1.2S", "PT9223372036854775808S", "PT-9223372036854775809S"}) @@ -449,6 +478,12 @@ class TestDriverAdapterCPDSReference { } } + /** + * Tests that legacy JNDI millisecond properties accept the full long integer range. + * + * @param millis the legacy timeout in milliseconds. + * @throws Exception if setting up, using, or closing the test resources fails. + */ @ParameterizedTest @ValueSource(longs = {Long.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE, 2_592_000_000L, Long.MAX_VALUE}) void testLegacyDurationReference(final long millis) throws Exception { @@ -460,6 +495,11 @@ class TestDriverAdapterCPDSReference { assertEquals(Duration.ofMillis(millis), restored.getMinEvictableIdleDuration()); } + /** + * Tests that valid duration properties take precedence over malformed legacy millisecond values. + * + * @throws Exception if setting up, using, or closing the test resources fails. + */ @Test void testModernDurationReferenceOverridesMalformedLegacyValues() throws Exception { final Reference reference = new Reference(DriverAdapterCPDS.class.getName(), DriverAdapterCPDS.class.getName(), null); @@ -472,6 +512,11 @@ class TestDriverAdapterCPDSReference { assertEquals(Duration.ofDays(30), restored.getMinEvictableIdleDuration()); } + /** + * Tests that null duration properties fall back to legacy millisecond values. + * + * @throws Exception if setting up, using, or closing the test resources fails. + */ @Test void testNullModernDurationReferenceFallsBackToLegacy() throws Exception { final Reference reference = new Reference(DriverAdapterCPDS.class.getName(), DriverAdapterCPDS.class.getName(), null); diff --git a/src/test/java/org/apache/commons/dbcp2/datasources/TestLoginTimeout.java b/src/test/java/org/apache/commons/dbcp2/datasources/TestLoginTimeout.java index 94fa5c56..2ad8f4e4 100644 --- a/src/test/java/org/apache/commons/dbcp2/datasources/TestLoginTimeout.java +++ b/src/test/java/org/apache/commons/dbcp2/datasources/TestLoginTimeout.java @@ -33,6 +33,7 @@ import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.sql.Connection; @@ -74,6 +75,13 @@ class TestLoginTimeout { /** Isolated JNDI lookup using only the environment supplied by each test. */ public static final class TestContextFactory implements InitialContextFactory { + /** + * Gets an isolated context that resolves the provider supplied in the test environment. + * + * @param environment the environment containing the provider under the {@code test.cpds} key. + * @return the context exposing the provider through the {@code timeoutTest} name. + * @throws NamingException if configuring the context lookup fails. + */ @Override public Context getInitialContext(final Hashtable<?, ?> environment) throws NamingException { final Context context = mock(Context.class); @@ -87,6 +95,11 @@ class TestLoginTimeout { private final List<Integer> attempts = new ArrayList<>(); private boolean enforceTimeout; + /** + * Constructs a provider that records login timeouts while delegating to the test JDBC driver. + * + * @throws ClassNotFoundException if the test JDBC driver cannot be loaded. + */ RecordingCpds() throws ClassNotFoundException { super(new DriverAdapterCPDS()); final DriverAdapterCPDS source = (DriverAdapterCPDS) delegate; @@ -96,23 +109,47 @@ class TestLoginTimeout { source.setPassword("p1"); } + /** + * Gets the current login timeout recorded by this provider. + * + * @return the login timeout in seconds. + */ @Override public int getLoginTimeout() { return timeout; } + /** + * Gets a pooled connection after recording the current login timeout. + * + * @return the pooled connection using the default credentials. + * @throws SQLException if the simulated timeout expires or the delegate cannot create a connection. + */ @Override public PooledConnection getPooledConnection() throws SQLException { recordAttempt(); return super.getPooledConnection(); } + /** + * Gets a pooled connection with explicit credentials after recording the current login timeout. + * + * @param user the user name. + * @param password the password. + * @return the pooled connection using the supplied credentials. + * @throws SQLException if the simulated timeout expires or the delegate cannot create a connection. + */ @Override public PooledConnection getPooledConnection(final String user, final String password) throws SQLException { recordAttempt(); return super.getPooledConnection(user, password); } + /** + * Records a connection attempt and optionally simulates expiration of a one-second timeout. + * + * @throws SQLTimeoutException if timeout enforcement is enabled and the current timeout is one second. + */ private void recordAttempt() throws SQLTimeoutException { attempts.add(timeout); if (enforceTimeout && timeout == 1) { @@ -120,6 +157,11 @@ class TestLoginTimeout { } } + /** + * Sets the login timeout recorded by this provider. + * + * @param seconds the login timeout in seconds. + */ @Override public void setLoginTimeout(final int seconds) { timeout = seconds; @@ -135,6 +177,11 @@ class TestLoginTimeout { private transient CountDownLatch release; private boolean equalToOtherProviders; + /** + * Constructs a serializable test provider with a nine-second default login timeout. + * + * @throws ClassNotFoundException if the test JDBC driver cannot be loaded. + */ SerializableCpds() throws ClassNotFoundException { setDriver(TesterDriver.class.getName()); setUrl("jdbc:apache:commons:testdriver"); @@ -143,6 +190,12 @@ class TestLoginTimeout { setLoginTimeout(9); } + /** + * Compares providers using the configured test equality mode and, when required, their login timeouts. + * + * @param other the object to compare with this provider. + * @return true if the other provider has the same equality mode and any required timeout values match. + */ @Override public boolean equals(final Object other) { if (!(other instanceof SerializableCpds)) { @@ -152,6 +205,12 @@ class TestLoginTimeout { return equalToOtherProviders == provider.equalToOtherProviders && (equalToOtherProviders || getLoginTimeout() == provider.getLoginTimeout()); } + /** + * Gets a pooled connection after recording the timeout and optionally waiting for a test signal. + * + * @return the pooled connection using the default credentials. + * @throws SQLException if waiting is interrupted or the test driver cannot create the connection. + */ @Override public PooledConnection getPooledConnection() throws SQLException { attempts.add(getLoginTimeout()); @@ -167,20 +226,52 @@ class TestLoginTimeout { return super.getPooledConnection(); } + /** + * Gets a constant or mutable hash code according to the configured test equality mode. + * + * @return one when all providers in this mode compare equal, or the current login timeout otherwise. + */ @Override public int hashCode() { return equalToOtherProviders ? 1 : getLoginTimeout(); } } + /** + * Supplies bounded and unbounded timeout settings for interruption tests. + * + * @return an unset timeout, zero, and a positive sub-second timeout. + */ static Stream<Duration> interruptedTimeouts() { return Stream.of(null, Duration.ZERO, Duration.ofMillis(100)); } + /** + * Supplies pool types and initial timeout settings for serialization tests. + * + * @return shared-pool and configured-timeout flag combinations. + */ static Stream<Arguments> serializationTimeouts() { return Stream.of(false, true).flatMap(shared -> Stream.of(false, true).map(configured -> Arguments.of(shared, configured))); } + /** + * Supplies pool types, provider lookup modes, and timeouts for serialization before provider configuration. + * + * @return configuration combinations and the timeout expected by the provider after deserialization. + */ + static Stream<Arguments> unregisteredSerializationTimeouts() { + return Stream.of(false, true).flatMap(shared -> Stream.of(false, true).flatMap(jndi -> + Stream.of(Arguments.of(null, 9), Arguments.of(Duration.ZERO, 0), Arguments.of(Duration.ofMillis(100), 1), + Arguments.of(Duration.ofSeconds(5), 5), Arguments.of(Duration.ofSeconds(Long.MAX_VALUE), Integer.MAX_VALUE)) + .map(timeout -> Arguments.of(shared, jndi, timeout.get()[0], timeout.get()[1])))); + } + + /** + * Supplies pool, lookup, credential, and timeout combinations for connection tests. + * + * @return connection configuration combinations and their expected JDBC timeout values. + */ static Stream<Arguments> loginTimeouts() { return Stream.of(false, true).flatMap(shared -> Stream.of(false, true).flatMap(jndi -> Stream.of(false, true) .flatMap(credentials -> Stream.of(Arguments.of(Duration.ZERO, 0), Arguments.of(Duration.ofNanos(1), 1), @@ -189,6 +280,13 @@ class TestLoginTimeout { .map(timeout -> Arguments.of(shared, jndi, credentials, timeout.get()[0], timeout.get()[1]))))); } + /** + * Creates a provider test double backed by a mutable login timeout. + * + * @param timeout the value read and updated by the timeout accessors. + * @return the provider test double. + * @throws SQLException if configuring the provider test double fails. + */ private static ConnectionPoolDataSource mockProvider(final AtomicInteger timeout) throws SQLException { final ConnectionPoolDataSource provider = mock(ConnectionPoolDataSource.class); when(provider.getLoginTimeout()).thenAnswer(invocation -> timeout.get()); @@ -199,8 +297,14 @@ class TestLoginTimeout { return provider; } - private static InstanceKeyDataSource newDataSource(final boolean shared, final boolean jndi, final ConnectionPoolDataSource provider) { - final InstanceKeyDataSource source = shared ? new SharedPoolDataSource() : new PerUserPoolDataSource(); + /** + * Configures a data source to obtain its provider directly or through JNDI and retain no idle connections. + * + * @param source the data source to configure before its pool is initialized. + * @param jndi whether to obtain the provider through JNDI. + * @param provider the physical connection provider. + */ + private static void configureDataSource(final InstanceKeyDataSource source, final boolean jndi, final ConnectionPoolDataSource provider) { if (jndi) { final Properties environment = new Properties(); environment.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestContextFactory.class.getName()); @@ -211,9 +315,57 @@ class TestLoginTimeout { source.setConnectionPoolDataSource(provider); } source.setDefaultMaxIdle(0); + } + + /** + * Deserializes a data source from its serialized representation. + * + * @param bytes the serialized data source. + * @return the restored data source. + * @throws IOException if the serialized data cannot be read. + * @throws ClassNotFoundException if a serialized class cannot be loaded. + */ + private static InstanceKeyDataSource deserialize(final byte[] bytes) throws IOException, ClassNotFoundException { + try (ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(bytes))) { + return (InstanceKeyDataSource) input.readObject(); + } + } + + /** + * Creates a data source that obtains its provider directly or through JNDI and retains no idle connections. + * + * @param shared whether to use a shared pool instead of per-user pools. + * @param jndi whether to obtain the provider through JNDI. + * @param provider the physical connection provider. + * @return the configured data source. + */ + private static InstanceKeyDataSource newDataSource(final boolean shared, final boolean jndi, final ConnectionPoolDataSource provider) { + final InstanceKeyDataSource source = shared ? new SharedPoolDataSource() : new PerUserPoolDataSource(); + configureDataSource(source, jndi, provider); return source; } + /** + * Serializes a data source without closing it or changing its registration. + * + * @param source the data source to serialize. + * @return the serialized representation. + * @throws IOException if the data source cannot be serialized. + */ + private static byte[] serialize(final InstanceKeyDataSource source) throws IOException { + final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (ObjectOutputStream output = new ObjectOutputStream(bytes)) { + output.writeObject(source); + } + return bytes.toByteArray(); + } + + /** + * Tests that a connection failure restores the provider's previous login timeout. + * + * @param credentials whether to use explicit user credentials. + * @throws SQLException if JDBC setup, an operation, or cleanup unexpectedly fails. + */ @ParameterizedTest @ValueSource(booleans = {false, true}) void testConnectionFailureRestoresProviderTimeout(final boolean credentials) throws SQLException { @@ -227,6 +379,11 @@ class TestLoginTimeout { assertEquals(9, timeout.get()); } + /** + * Tests that a timeout restoration failure is suppressed on the original connection failure. + * + * @throws SQLException if JDBC setup, an operation, or cleanup unexpectedly fails. + */ @Test void testConnectionFailureSuppressesRestoreFailure() throws SQLException { final ConnectionPoolDataSource provider = mock(ConnectionPoolDataSource.class); @@ -240,6 +397,11 @@ class TestLoginTimeout { assertEquals(Arrays.asList(restoreFailure), Arrays.asList(failure.getSuppressed())); } + /** + * Tests that an unchanged login timeout avoids a provider setter call. + * + * @throws SQLException if JDBC setup, an operation, or cleanup unexpectedly fails. + */ @Test void testEqualTimeoutDoesNotCallSetter() throws SQLException { final ConnectionPoolDataSource provider = mock(ConnectionPoolDataSource.class); @@ -248,6 +410,16 @@ class TestLoginTimeout { verify(provider, never()).setLoginTimeout(anyInt()); } + /** + * Tests timeout conversion and live configuration changes for initial and later physical connections. + * + * @param shared whether to use a shared pool instead of per-user pools. + * @param jndi whether to obtain the provider through JNDI. + * @param credentials whether to use explicit user credentials. + * @param duration the duration under test. + * @param expected the expected timeout passed to JDBC, in seconds. + * @throws Exception if setting up, using, or closing the test resources fails. + */ @ParameterizedTest @MethodSource("loginTimeouts") void testLoginTimeoutForInitialAndLaterConnections(final boolean shared, final boolean jndi, final boolean credentials, @@ -274,6 +446,12 @@ class TestLoginTimeout { } } + /** + * Tests that invalid login timeouts are rejected without changing the current setting. + * + * @param shared whether to use a shared pool instead of per-user pools. + * @throws Exception if setting up, using, or closing the test resources fails. + */ @ParameterizedTest @ValueSource(booleans = {false, true}) void testLoginTimeoutRejectsInvalidValues(final boolean shared) throws Exception { @@ -286,6 +464,11 @@ class TestLoginTimeout { } } + /** + * Tests that a restoration failure closes the acquired connection and retains a subsequent close failure. + * + * @throws SQLException if JDBC setup, an operation, or cleanup unexpectedly fails. + */ @Test void testRestoreFailureClosesConnectionAndSuppressesCloseFailure() throws SQLException { final ConnectionPoolDataSource provider = mock(ConnectionPoolDataSource.class); @@ -302,6 +485,11 @@ class TestLoginTimeout { assertEquals(Arrays.asList(closeFailure), Arrays.asList(restoreFailure.getSuppressed())); } + /** + * Tests timeout restoration when the provider setter changes its state before failing. + * + * @throws SQLException if JDBC setup, an operation, or cleanup unexpectedly fails. + */ @Test void testSetterFailureRestoresProviderTimeout() throws SQLException { final AtomicInteger timeout = new AtomicInteger(9); @@ -317,6 +505,12 @@ class TestLoginTimeout { verify(provider, never()).getPooledConnection(); } + /** + * Tests that temporary timeout overrides exclude overlapping attempts through the same provider. + * + * @param secondUsesProviderDefault whether the second attempt leaves the provider timeout unconfigured. + * @throws Exception if a JDBC operation or worker task fails, times out, or is interrupted. + */ @ParameterizedTest @ValueSource(booleans = {false, true}) void testSharedProviderSerializesTemporaryTimeouts(final boolean secondUsesProviderDefault) throws Exception { @@ -359,6 +553,11 @@ class TestLoginTimeout { } } + /** + * Tests that an unset login timeout avoids reading or changing the provider's setting. + * + * @throws SQLException if JDBC setup, an operation, or cleanup unexpectedly fails. + */ @Test void testUnconfiguredTimeoutDoesNotCallProviderTimeoutMethods() throws SQLException { final ConnectionPoolDataSource provider = mock(ConnectionPoolDataSource.class); @@ -368,6 +567,12 @@ class TestLoginTimeout { verify(provider, never()).setLoginTimeout(anyInt()); } + /** + * Tests that an unset login timeout preserves the provider default during physical connection creation. + * + * @param shared whether to use a shared pool instead of per-user pools. + * @throws Exception if setting up, using, or closing the test resources fails. + */ @ParameterizedTest @ValueSource(booleans = {false, true}) void testUnconfiguredTimeoutPreservesProviderDefault(final boolean shared) throws Exception { @@ -380,10 +585,21 @@ class TestLoginTimeout { } } + /** + * Supplies unchecked failures that a provider may throw while connecting. + * + * @return a runtime exception and an error. + */ static Stream<Throwable> uncheckedFailures() { return Stream.of(new IllegalStateException("Driver failure"), new AssertionError("Driver error")); } + /** + * Tests that unchecked connection failures preserve their identity and restore the provider timeout. + * + * @param failure the unchecked failure thrown by the provider. + * @throws SQLException if JDBC setup, an operation, or cleanup unexpectedly fails. + */ @ParameterizedTest @MethodSource("uncheckedFailures") void testUncheckedConnectionFailureRestoresTimeout(final Throwable failure) throws SQLException { @@ -395,6 +611,11 @@ class TestLoginTimeout { assertEquals(9, timeout.get()); } + /** + * Tests that reusing the same driver exception for connection and restoration failures avoids self-suppression. + * + * @throws SQLException if JDBC setup, an operation, or cleanup unexpectedly fails. + */ @Test void testRepeatedDriverExceptionDoesNotSuppressItself() throws SQLException { final ConnectionPoolDataSource provider = mock(ConnectionPoolDataSource.class); @@ -407,6 +628,12 @@ class TestLoginTimeout { assertEquals(0, failure.getSuppressed().length); } + /** + * Tests that provider-enforced login timeouts apply before and after pool initialization. + * + * @param shared whether to use a shared pool instead of per-user pools. + * @throws Exception if setting up, using, or closing the test resources fails. + */ @ParameterizedTest @ValueSource(booleans = {false, true}) void testProviderEnforcesTimeoutForInitialAndLaterConnections(final boolean shared) throws Exception { @@ -428,6 +655,13 @@ class TestLoginTimeout { } } + /** + * Tests that deserialized wrappers and their original data sources share live login timeout changes. + * + * @param shared whether to use a shared pool instead of per-user pools. + * @param configured whether to configure a timeout before serializing the data source. + * @throws Exception if serialization, deserialization, or a JDBC operation fails. + */ @ParameterizedTest @MethodSource("serializationTimeouts") void testDeserializedWrappersShareLiveLoginTimeout(final boolean shared, final boolean configured) throws Exception { @@ -439,12 +673,7 @@ class TestLoginTimeout { try (Connection connection = source.getConnection()) { assertFalse(connection.isClosed()); } - final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - try (ObjectOutputStream output = new ObjectOutputStream(bytes)) { - output.writeObject(source); - } - try (ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())); - InstanceKeyDataSource restored = (InstanceKeyDataSource) input.readObject()) { + try (InstanceKeyDataSource restored = deserialize(serialize(source))) { assertEquals(source.getLoginTimeoutDuration(), restored.getLoginTimeoutDuration()); restored.setLoginTimeout(Duration.ofSeconds(3)); assertEquals(Duration.ofSeconds(3), source.getLoginTimeoutDuration()); @@ -467,6 +696,84 @@ class TestLoginTimeout { } } + /** + * Tests that registered data sources share live timeouts after deserialization even before their pools are initialized. + * + * @param shared whether to use a shared pool instead of per-user pools. + * @param configured whether to configure a timeout before serializing the data source. + * @throws Exception if serialization, deserialization, or closing the data source fails. + */ + @ParameterizedTest + @MethodSource("serializationTimeouts") + void testRegisteredSerializationSharesTimeoutBeforePoolInitialization(final boolean shared, final boolean configured) throws Exception { + try (InstanceKeyDataSource source = newDataSource(shared, false, new SerializableCpds())) { + if (configured) { + source.setLoginTimeout(Duration.ofSeconds(5)); + } + final byte[] bytes = serialize(source); + source.setLoginTimeout(Duration.ofSeconds(7)); + try (InstanceKeyDataSource restored = deserialize(bytes)) { + assertEquals(Duration.ofSeconds(7), restored.getConfiguredLoginTimeout()); + restored.setLoginTimeout(Duration.ofSeconds(3)); + assertEquals(Duration.ofSeconds(3), source.getConfiguredLoginTimeout()); + } + } + } + + /** + * Tests that repeated serialization before provider configuration preserves an independent local timeout setting. + * + * @param shared whether to use a shared pool instead of per-user pools. + * @param jndi whether to configure the restored provider through JNDI. + * @param timeout the serialized timeout, or {@code null} to retain the provider's setting. + * @param expected the timeout expected by the provider, in seconds. + * @throws Exception if serialization, provider configuration, or a JDBC operation fails. + */ + @ParameterizedTest + @MethodSource("unregisteredSerializationTimeouts") + void testUnregisteredSerializationRetainsLoginTimeout(final boolean shared, final boolean jndi, final Duration timeout, final int expected) + throws Exception { + try (InstanceKeyDataSource source = shared ? new SharedPoolDataSource() : new PerUserPoolDataSource()) { + if (timeout != null) { + source.setLoginTimeout(timeout); + } + final byte[] bytes = serialize(source); + source.setLoginTimeout(Duration.ofSeconds(11)); + try (InstanceKeyDataSource restored = deserialize(bytes)) { + assertEquals(timeout, restored.getConfiguredLoginTimeout()); + assertEquals(timeout == null ? Duration.ZERO : timeout, restored.getLoginTimeoutDuration()); + try (InstanceKeyDataSource repeated = deserialize(serialize(restored))) { + restored.setLoginTimeout(Duration.ofSeconds(13)); + assertEquals(timeout, repeated.getConfiguredLoginTimeout()); + final RecordingCpds provider = new RecordingCpds(); + configureDataSource(repeated, jndi, provider); + try (Connection connection = repeated.getConnection()) { + assertFalse(connection.isClosed()); + } + assertFalse(provider.attempts.isEmpty()); + provider.attempts.forEach(value -> assertEquals(expected, value.intValue())); + assertEquals(9, provider.getLoginTimeout()); + provider.attempts.clear(); + repeated.setLoginTimeout(Duration.ofSeconds(3)); + try (Connection connection = repeated.getConnection()) { + assertFalse(connection.isClosed()); + } + assertFalse(provider.attempts.isEmpty()); + provider.attempts.forEach(value -> assertEquals(3, value.intValue())); + assertEquals(9, provider.getLoginTimeout()); + assertEquals(Duration.ofSeconds(13), restored.getConfiguredLoginTimeout()); + assertEquals(Duration.ofSeconds(11), source.getConfiguredLoginTimeout()); + } + } + } + } + + /** + * Tests provider lock isolation by identity despite mutable hashes or equality between distinct providers. + * + * @param sameProvider whether both attempts use the same provider instance. + * @throws Exception if a JDBC operation or worker task fails, times out, or is interrupted. + */ @ParameterizedTest @ValueSource(booleans = {false, true}) void testProviderLocksUseIdentity(final boolean sameProvider) throws Exception { @@ -503,6 +810,12 @@ class TestLoginTimeout { } } + /** + * Tests that interrupted lock acquisition preserves the interrupt flag and avoids provider access. + * + * @param timeout the provider lock timeout, or {@code null} for an unbounded read-lock wait. + * @throws SQLException if JDBC setup, an operation, or cleanup unexpectedly fails. + */ @ParameterizedTest @MethodSource("interruptedTimeouts") void testProviderLockPreservesInterruption(final Duration timeout) throws SQLException { @@ -520,6 +833,11 @@ class TestLoginTimeout { } } + /** + * Tests that a positive login timeout bounds the wait for another attempt to release the provider lock. + * + * @throws Exception if a JDBC operation or worker task fails, times out, or is interrupted. + */ @Test void testWaitingForProviderHonorsPositiveTimeout() throws Exception { final SerializableCpds provider = new SerializableCpds(); @@ -543,6 +861,12 @@ class TestLoginTimeout { } } + /** + * Tests that each provider failure path releases the lock for a subsequent attempt from another thread. + * + * @param phase the failing operation: reading, setting, connecting, or restoring the timeout. + * @throws Exception if a JDBC operation or worker task fails, times out, or is interrupted. + */ @ParameterizedTest @ValueSource(strings = {"read", "set", "connect", "restore"}) void testProviderLockReleasedAfterFailure(final String phase) throws Exception {
