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
The following commit(s) were added to refs/heads/master by this push:
new 986c33a7 Sort members
986c33a7 is described below
commit 986c33a726fdd2f6d6f560041c5fc23b45277a2a
Author: Gary Gregory <[email protected]>
AuthorDate: Mon Nov 23 12:14:34 2026 -0500
Sort members
---
.../apache/commons/dbcp2/DelegatingConnection.java | 32 +-
.../commons/dbcp2/DelegatingDatabaseMetaData.java | 20 +-
.../apache/commons/dbcp2/DelegatingResultSet.java | 36 +-
.../apache/commons/dbcp2/DelegatingStatement.java | 26 +-
.../org/apache/commons/dbcp2/DriverFactory.java | 12 +-
.../apache/commons/dbcp2/ObjectNameWrapper.java | 18 +-
src/main/java/org/apache/commons/dbcp2/Utils.java | 26 +-
.../dbcp2/cpdsadapter/DriverAdapterCPDS.java | 24 +-
.../dbcp2/datasources/InstanceKeyDataSource.java | 28 +-
.../apache/commons/dbcp2/TestBasicDataSource.java | 18 +-
.../dbcp2/TestBasicDataSourceInvalidation.java | 20 +-
.../apache/commons/dbcp2/TestDelegateChains.java | 10 +-
.../apache/commons/dbcp2/TestDriverFactory.java | 56 +-
.../org/apache/commons/dbcp2/TestJdbcTimeouts.java | 230 +++----
.../commons/dbcp2/TestObjectNameWrapper.java | 36 +-
.../commons/dbcp2/TestPoolableConnection.java | 4 +-
.../commons/dbcp2/TestPoolingDataSource.java | 58 +-
.../TestDriverAdapterCPDSReference.java | 326 +++++-----
.../dbcp2/datasources/TestLoginTimeout.java | 692 ++++++++++-----------
19 files changed, 836 insertions(+), 836 deletions(-)
diff --git a/src/main/java/org/apache/commons/dbcp2/DelegatingConnection.java
b/src/main/java/org/apache/commons/dbcp2/DelegatingConnection.java
index 7a5a7b05..b419bd77 100644
--- a/src/main/java/org/apache/commons/dbcp2/DelegatingConnection.java
+++ b/src/main/java/org/apache/commons/dbcp2/DelegatingConnection.java
@@ -600,6 +600,22 @@ public class DelegatingConnection<C extends Connection>
extends AbandonedTrace i
return innerCon.equals(c);
}
+ /**
+ * Tests whether this wrapper allows access to its underlying connection.
+ * <p>
+ * This policy applies to delegate getters and JDBC unwrapping on this
connection and its statements, result sets, and database metadata.
+ * Unwrapping an interface implemented by the wrapper itself remains
allowed. The default implementation returns {@code true}; pool guard
+ * wrappers override it to consult their configuration. This policy helps
prevent accidental misuse and is not a security boundary against
+ * code running in the same JVM. Internal accessors used by pool lifecycle
operations bypass it.
+ * </p>
+ *
+ * @return true if access to the underlying connection is allowed.
+ * @since 2.15.0
+ */
+ protected boolean isAccessToUnderlyingConnectionAllowed() {
+ return true;
+ }
+
@Override
public boolean isClosed() throws SQLException {
return closed || connection == null || connection.isClosed();
@@ -668,22 +684,6 @@ public class DelegatingConnection<C extends Connection>
extends AbandonedTrace i
return isValid(Duration.ofSeconds(timeoutSeconds));
}
- /**
- * Tests whether this wrapper allows access to its underlying connection.
- * <p>
- * This policy applies to delegate getters and JDBC unwrapping on this
connection and its statements, result sets, and database metadata.
- * Unwrapping an interface implemented by the wrapper itself remains
allowed. The default implementation returns {@code true}; pool guard
- * wrappers override it to consult their configuration. This policy helps
prevent accidental misuse and is not a security boundary against
- * code running in the same JVM. Internal accessors used by pool lifecycle
operations bypass it.
- * </p>
- *
- * @return true if access to the underlying connection is allowed.
- * @since 2.15.0
- */
- protected boolean isAccessToUnderlyingConnectionAllowed() {
- return true;
- }
-
@Override
public boolean isWrapperFor(final Class<?> iface) throws SQLException {
if (iface.isAssignableFrom(getClass())) {
diff --git
a/src/main/java/org/apache/commons/dbcp2/DelegatingDatabaseMetaData.java
b/src/main/java/org/apache/commons/dbcp2/DelegatingDatabaseMetaData.java
index 0c910534..4ac61168 100644
--- a/src/main/java/org/apache/commons/dbcp2/DelegatingDatabaseMetaData.java
+++ b/src/main/java/org/apache/commons/dbcp2/DelegatingDatabaseMetaData.java
@@ -276,16 +276,6 @@ public class DelegatingDatabaseMetaData implements
DatabaseMetaData {
return Utils.getInnermostDelegate(this,
DelegatingDatabaseMetaData.class, DelegatingDatabaseMetaData::getDelegate);
}
- /**
- * Tests whether access to the underlying {@link DatabaseMetaData} is
allowed, consulting the connection that
- * created me.
- *
- * @return false only when the connection that created me forbids access
to the underlying connection.
- */
- private boolean isAccessToUnderlyingConnectionAllowed() {
- return connection.isAccessToUnderlyingConnectionAllowed();
- }
-
@Override
public int getJDBCMajorVersion() throws SQLException {
return getI(databaseMetaData::getJDBCMajorVersion);
@@ -569,6 +559,16 @@ public class DelegatingDatabaseMetaData implements
DatabaseMetaData {
return getB(() -> databaseMetaData.insertsAreDetected(type));
}
+ /**
+ * Tests whether access to the underlying {@link DatabaseMetaData} is
allowed, consulting the connection that
+ * created me.
+ *
+ * @return false only when the connection that created me forbids access
to the underlying connection.
+ */
+ private boolean isAccessToUnderlyingConnectionAllowed() {
+ return connection.isAccessToUnderlyingConnectionAllowed();
+ }
+
@Override
public boolean isCatalogAtStart() throws SQLException {
return getB(databaseMetaData::isCatalogAtStart);
diff --git a/src/main/java/org/apache/commons/dbcp2/DelegatingResultSet.java
b/src/main/java/org/apache/commons/dbcp2/DelegatingResultSet.java
index c8b3bce7..31f2d877 100644
--- a/src/main/java/org/apache/commons/dbcp2/DelegatingResultSet.java
+++ b/src/main/java/org/apache/commons/dbcp2/DelegatingResultSet.java
@@ -608,24 +608,6 @@ public final class DelegatingResultSet extends
AbandonedTrace implements ResultS
return Utils.getInnermostDelegate(this, DelegatingResultSet.class,
DelegatingResultSet::getDelegate);
}
- /**
- * Tests whether access to the underlying {@link ResultSet} is allowed.
- * <p>
- * Consults the creating statement or connection while it is attached, and
retains the last policy when close clears those references.
- * </p>
- *
- * @return true if access to the underlying result set is allowed.
- */
- private boolean isAccessToUnderlyingConnectionAllowed() {
- if (statement instanceof DelegatingStatement) {
- return ((DelegatingStatement)
statement).isAccessToUnderlyingConnectionAllowed();
- }
- if (connection instanceof DelegatingConnection) {
- return ((DelegatingConnection<?>)
connection).isAccessToUnderlyingConnectionAllowed();
- }
- return accessToUnderlyingConnectionAllowed;
- }
-
@Override
public int getInt(final int columnIndex) throws SQLException {
try {
@@ -1080,6 +1062,24 @@ public final class DelegatingResultSet extends
AbandonedTrace implements ResultS
}
}
+ /**
+ * Tests whether access to the underlying {@link ResultSet} is allowed.
+ * <p>
+ * Consults the creating statement or connection while it is attached, and
retains the last policy when close clears those references.
+ * </p>
+ *
+ * @return true if access to the underlying result set is allowed.
+ */
+ private boolean isAccessToUnderlyingConnectionAllowed() {
+ if (statement instanceof DelegatingStatement) {
+ return ((DelegatingStatement)
statement).isAccessToUnderlyingConnectionAllowed();
+ }
+ if (connection instanceof DelegatingConnection) {
+ return ((DelegatingConnection<?>)
connection).isAccessToUnderlyingConnectionAllowed();
+ }
+ return accessToUnderlyingConnectionAllowed;
+ }
+
@Override
public boolean isAfterLast() throws SQLException {
try {
diff --git a/src/main/java/org/apache/commons/dbcp2/DelegatingStatement.java
b/src/main/java/org/apache/commons/dbcp2/DelegatingStatement.java
index d123ecb8..bce6386d 100644
--- a/src/main/java/org/apache/commons/dbcp2/DelegatingStatement.java
+++ b/src/main/java/org/apache/commons/dbcp2/DelegatingStatement.java
@@ -497,19 +497,6 @@ public class DelegatingStatement extends AbandonedTrace
implements Statement {
return Utils.getInnermostDelegate(this, DelegatingStatement.class,
DelegatingStatement::getDelegateInternal);
}
- /**
- * Tests whether access to the underlying {@link Statement} is allowed.
- * <p>
- * Consults the creating connection while it is attached, and retains the
last policy when close clears that reference.
- * </p>
- *
- * @return true if access to the underlying statement is allowed.
- * @since 2.15.0
- */
- protected boolean isAccessToUnderlyingConnectionAllowed() {
- return connection == null ? accessToUnderlyingConnectionAllowed :
connection.isAccessToUnderlyingConnectionAllowed();
- }
-
/**
* @since 2.5.0
*/
@@ -673,6 +660,19 @@ public class DelegatingStatement extends AbandonedTrace
implements Statement {
connection.handleException(e);
}
+ /**
+ * Tests whether access to the underlying {@link Statement} is allowed.
+ * <p>
+ * Consults the creating connection while it is attached, and retains the
last policy when close clears that reference.
+ * </p>
+ *
+ * @return true if access to the underlying statement is allowed.
+ * @since 2.15.0
+ */
+ protected boolean isAccessToUnderlyingConnectionAllowed() {
+ return connection == null ? accessToUnderlyingConnectionAllowed :
connection.isAccessToUnderlyingConnectionAllowed();
+ }
+
/*
* Note: This method was protected prior to JDBC 4.
*/
diff --git a/src/main/java/org/apache/commons/dbcp2/DriverFactory.java
b/src/main/java/org/apache/commons/dbcp2/DriverFactory.java
index acbe1631..ca969352 100644
--- a/src/main/java/org/apache/commons/dbcp2/DriverFactory.java
+++ b/src/main/java/org/apache/commons/dbcp2/DriverFactory.java
@@ -72,12 +72,6 @@ final class DriverFactory {
*/
private static final String SQL_STATE_UNABLE_TO_CONNECT = "08001";
- /**
- * Constructs a driver factory.
- */
- DriverFactory() {
- }
-
/**
* Selects the JDBC driver for a data source, creating an instance when a
driver class name is configured.
* <p>
@@ -142,4 +136,10 @@ final class DriverFactory {
}
return driver;
}
+
+ /**
+ * Constructs a driver factory.
+ */
+ DriverFactory() {
+ }
}
diff --git a/src/main/java/org/apache/commons/dbcp2/ObjectNameWrapper.java
b/src/main/java/org/apache/commons/dbcp2/ObjectNameWrapper.java
index 40fbd93f..990e558d 100644
--- a/src/main/java/org/apache/commons/dbcp2/ObjectNameWrapper.java
+++ b/src/main/java/org/apache/commons/dbcp2/ObjectNameWrapper.java
@@ -80,24 +80,24 @@ final class ObjectNameWrapper {
}
/**
- * Wraps an object name using the platform MBean server.
+ * Wraps an object name using the supplied MBean server.
*
+ * @param server The server to use, may be {@code null} to disable
registration and unregistration; no platform server fallback is performed.
* @param objectName The object name, may be {@code null} to disable
registration and unregistration.
- * @return A new wrapper for the name, associated with the platform MBean
server or a {@code null} server if unavailable.
+ * @return A new wrapper using the supplied server and name.
*/
- static ObjectNameWrapper wrap(final ObjectName objectName) {
- return new ObjectNameWrapper(MBEAN_SERVER, objectName);
+ static ObjectNameWrapper wrap(final MBeanServer server, final ObjectName
objectName) {
+ return new ObjectNameWrapper(server, objectName);
}
/**
- * Wraps an object name using the supplied MBean server.
+ * Wraps an object name using the platform MBean server.
*
- * @param server The server to use, may be {@code null} to disable
registration and unregistration; no platform server fallback is performed.
* @param objectName The object name, may be {@code null} to disable
registration and unregistration.
- * @return A new wrapper using the supplied server and name.
+ * @return A new wrapper for the name, associated with the platform MBean
server or a {@code null} server if unavailable.
*/
- static ObjectNameWrapper wrap(final MBeanServer server, final ObjectName
objectName) {
- return new ObjectNameWrapper(server, objectName);
+ static ObjectNameWrapper wrap(final ObjectName objectName) {
+ return new ObjectNameWrapper(MBEAN_SERVER, objectName);
}
/**
diff --git a/src/main/java/org/apache/commons/dbcp2/Utils.java
b/src/main/java/org/apache/commons/dbcp2/Utils.java
index 48c095b8..b0bf6d14 100644
--- a/src/main/java/org/apache/commons/dbcp2/Utils.java
+++ b/src/main/java/org/apache/commons/dbcp2/Utils.java
@@ -233,19 +233,6 @@ public final class Utils {
closeQuietly((AutoCloseable) statement);
}
- /**
- * Finds the first matching object in a chain, visiting each object by
identity at most once.
- *
- * @param <T> the chain element type.
- * @param start the first object to inspect, which may be null.
- * @param matches tests whether the current object is the desired result.
- * @param next gets the next object in the chain.
- * @return the first match, or null if the chain ends or cycles before a
match is found.
- */
- static <T> T findInChain(final T start, final Predicate<? super T>
matches, final Function<? super T, ? extends T> next) {
- return Utils.<T, RuntimeException>findInChain(start, matches::test,
next::apply, current -> null);
- }
-
/**
* Finds the first matching object in a chain, allowing checked exceptions
and caller-specific cycle handling.
*
@@ -274,6 +261,19 @@ public final class Utils {
return null;
}
+ /**
+ * Finds the first matching object in a chain, visiting each object by
identity at most once.
+ *
+ * @param <T> the chain element type.
+ * @param start the first object to inspect, which may be null.
+ * @param matches tests whether the current object is the desired result.
+ * @param next gets the next object in the chain.
+ * @return the first match, or null if the chain ends or cycles before a
match is found.
+ */
+ static <T> T findInChain(final T start, final Predicate<? super T>
matches, final Function<? super T, ? extends T> next) {
+ return Utils.<T, RuntimeException>findInChain(start, matches::test,
next::apply, current -> null);
+ }
+
/**
* Gets a copy of SQL codes of fatal connection errors.
* <ul>
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 1ed087e2..479a0c57 100644
--- a/src/main/java/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS.java
+++ b/src/main/java/org/apache/commons/dbcp2/cpdsadapter/DriverAdapterCPDS.java
@@ -252,18 +252,6 @@ public class DriverAdapterCPDS implements
ConnectionPoolDataSource, Referenceabl
return driver;
}
- /**
- * Gets the duration 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 #setDurationBetweenEvictionRuns(Duration)
- * @since 2.9.0
- */
- public Duration getDurationBetweenEvictionRuns() {
- return durationBetweenEvictionRuns;
- }
-
/**
* Gets a duration from a JNDI Reference, preferring the ISO-8601 property
over the legacy millisecond property.
*
@@ -283,6 +271,18 @@ public class DriverAdapterCPDS implements
ConnectionPoolDataSource, Referenceabl
return isNotEmpty(millis) ?
Duration.ofMillis(Long.parseLong(getStringContent(millis))) : null;
}
+ /**
+ * Gets the duration 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 #setDurationBetweenEvictionRuns(Duration)
+ * @since 2.9.0
+ */
+ public Duration getDurationBetweenEvictionRuns() {
+ return durationBetweenEvictionRuns;
+ }
+
private int getIntegerStringContent(final RefAddr ra) {
return Integer.parseInt(getStringContent(ra));
}
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 19dfb5c4..f5a564af 100644
---
a/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java
+++
b/src/main/java/org/apache/commons/dbcp2/datasources/InstanceKeyDataSource.java
@@ -219,6 +219,20 @@ public abstract class InstanceKeyDataSource implements
DataSource, Referenceable
}
}
+ /**
+ * 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();
+ }
+
/**
* Attempts to establish a database connection.
*/
@@ -321,20 +335,6 @@ public abstract class InstanceKeyDataSource implements
DataSource, Referenceable
*/
protected abstract PooledConnectionManager
getConnectionManager(UserPassKey upkey);
- /**
- * 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();
- }
-
/**
* Gets the value of connectionPoolDataSource. This method will return
null, if the backing data source is being
* accessed via JNDI.
diff --git a/src/test/java/org/apache/commons/dbcp2/TestBasicDataSource.java
b/src/test/java/org/apache/commons/dbcp2/TestBasicDataSource.java
index 952c5a5f..3d365c34 100644
--- a/src/test/java/org/apache/commons/dbcp2/TestBasicDataSource.java
+++ b/src/test/java/org/apache/commons/dbcp2/TestBasicDataSource.java
@@ -1152,6 +1152,15 @@ public class TestBasicDataSource extends
TestConnectionPool {
}
}
+ @Test
+ void testValidationQueryTimeoutSubSecondFail() {
+ ds.setTestOnBorrow(true);
+ // A positive sub-second timeout must not be truncated to 0 (no
timeout); it becomes 1 second, too fast for TesterStatement.
+ ds.setValidationQueryTimeout(Duration.ofMillis(100));
+ final SQLException e = assertThrows(SQLException.class,
ds::getConnection);
+ assertTrue(e.toString().contains("timeout"));
+ }
+
@Test
void testValidationQueryTimeoutSucceed() throws Exception {
ds.setTestOnBorrow(true);
@@ -1162,15 +1171,6 @@ public class TestBasicDataSource extends
TestConnectionPool {
}
}
- @Test
- void testValidationQueryTimeoutSubSecondFail() {
- ds.setTestOnBorrow(true);
- // A positive sub-second timeout must not be truncated to 0 (no
timeout); it becomes 1 second, too fast for TesterStatement.
- ds.setValidationQueryTimeout(Duration.ofMillis(100));
- final SQLException e = assertThrows(SQLException.class,
ds::getConnection);
- assertTrue(e.toString().contains("timeout"));
- }
-
@Test
void testValidationQueryTimeoutZero() throws Exception {
ds.setTestOnBorrow(true);
diff --git
a/src/test/java/org/apache/commons/dbcp2/TestBasicDataSourceInvalidation.java
b/src/test/java/org/apache/commons/dbcp2/TestBasicDataSourceInvalidation.java
index cd1c3bb5..e9652193 100644
---
a/src/test/java/org/apache/commons/dbcp2/TestBasicDataSourceInvalidation.java
+++
b/src/test/java/org/apache/commons/dbcp2/TestBasicDataSourceInvalidation.java
@@ -69,13 +69,9 @@ class TestBasicDataSourceInvalidation {
private static final AtomicInteger IDS = new AtomicInteger();
private static final Duration TIMEOUT = Duration.ofSeconds(5);
- private BasicDataSource dataSource;
- private Connection pooledConnection;
-
private static Stream<Arguments> acyclicArguments() {
return Stream.of(0, 1, 2, 16, 256).flatMap(length -> Stream.of(false,
true).map(external -> Arguments.of(length, external)));
}
-
private static Stream<Arguments> cyclicArguments() {
return Stream.of(0, 1, 8).flatMap(prefixLength -> Stream.of(1, 2, 3,
16).flatMap(cycleLength ->
Stream.of(false, true).flatMap(external -> Stream.of(false,
true).map(bridged -> Arguments.of(prefixLength, cycleLength, external,
bridged)))));
@@ -92,6 +88,10 @@ class TestBasicDataSourceInvalidation {
});
}
+ private BasicDataSource dataSource;
+
+ private Connection pooledConnection;
+
private void assertCyclicChain(final int prefixLength, final int
cycleLength, final boolean external, final boolean bridged) throws SQLException
{
final List<DelegatingConnection<Connection>> nodes = new ArrayList<>();
for (int i = 0; i < prefixLength + cycleLength; i++) {
@@ -225,6 +225,12 @@ class TestBasicDataSourceInvalidation {
assertTrue(pooledConnection.isValid(1));
}
+ @Test
+ void testInvalidateInteriorCycle() throws SQLException {
+ // A -> B -> C -> B never returns to A and has no self-loop.
+ assertCyclicChain(1, 2, false, false);
+ }
+
@ParameterizedTest
@ValueSource(ints = {1, 2, 16})
void testInvalidateInterleavedWrappers(final int length) throws
SQLException {
@@ -238,12 +244,6 @@ class TestBasicDataSourceInvalidation {
assertTrue(pooledConnection.isClosed());
}
- @Test
- void testInvalidateInteriorCycle() throws SQLException {
- // A -> B -> C -> B never returns to A and has no self-loop.
- assertCyclicChain(1, 2, false, false);
- }
-
@ParameterizedTest
@ValueSource(ints = {1, 2, 16})
void testInvalidateNullTerminatedChain(final int length) {
diff --git a/src/test/java/org/apache/commons/dbcp2/TestDelegateChains.java
b/src/test/java/org/apache/commons/dbcp2/TestDelegateChains.java
index 6b794c94..5412bf9a 100644
--- a/src/test/java/org/apache/commons/dbcp2/TestDelegateChains.java
+++ b/src/test/java/org/apache/commons/dbcp2/TestDelegateChains.java
@@ -192,11 +192,6 @@ class TestDelegateChains {
assertSame(kind.internal ? terminal : null, kind.innermost(head));
}
- @Test
- void testInteriorConnectionCycle() throws Exception {
- testCyclicChain(Kind.CONNECTION, 1, 2);
- }
-
@Test
void testIdentityRatherThanEquality() throws Exception {
final Object terminal = Kind.CONNECTION.terminal();
@@ -217,4 +212,9 @@ class TestDelegateChains {
assertSame(terminal, Kind.CONNECTION.innermost(head));
assertSame(terminal, Kind.CONNECTION_INTERNAL.innermost(head));
}
+
+ @Test
+ void testInteriorConnectionCycle() throws Exception {
+ testCyclicChain(Kind.CONNECTION, 1, 2);
+ }
}
diff --git a/src/test/java/org/apache/commons/dbcp2/TestDriverFactory.java
b/src/test/java/org/apache/commons/dbcp2/TestDriverFactory.java
index 9c135272..4810237d 100644
--- a/src/test/java/org/apache/commons/dbcp2/TestDriverFactory.java
+++ b/src/test/java/org/apache/commons/dbcp2/TestDriverFactory.java
@@ -559,6 +559,24 @@ public class TestDriverFactory {
}
}
+ @ParameterizedTest
+ @EnumSource(LoaderMode.class)
+ void testCreateDriver(final LoaderMode loaderMode) throws SQLException {
+ final Class<? extends Driver> driverClass = loaderMode.driverClass;
+ assertFalse(INITIALIZED_CLASSES.contains(driverClass));
+ assertFalse(CONSTRUCTED_CLASSES.contains(driverClass));
+ try (BasicDataSource dataSource = new BasicDataSource(); LoaderScope
loaders = new LoaderScope(dataSource, loaderMode)) {
+ dataSource.setDriverClassName(driverClass.getName());
+ dataSource.setUrl(URL);
+ final Driver driver = DriverFactory.createDriver(dataSource);
+ assertSame(driverClass, driver.getClass());
+ assertTrue(INITIALIZED_CLASSES.contains(driverClass));
+ assertTrue(CONSTRUCTED_CLASSES.contains(driverClass));
+ assertTrue(driver.acceptsURL(URL));
+ loaders.assertUsed(driverClass.getName());
+ }
+ }
+
@ParameterizedTest(name = "{0}, nonDriver={1}")
@MethodSource("definingLoaderCases")
void testDefiningClassLoader(final LoaderMode loaderMode, final boolean
nonDriver) throws Exception {
@@ -598,24 +616,6 @@ public class TestDriverFactory {
}
}
- @ParameterizedTest
- @EnumSource(LoaderMode.class)
- void testCreateDriver(final LoaderMode loaderMode) throws SQLException {
- final Class<? extends Driver> driverClass = loaderMode.driverClass;
- assertFalse(INITIALIZED_CLASSES.contains(driverClass));
- assertFalse(CONSTRUCTED_CLASSES.contains(driverClass));
- try (BasicDataSource dataSource = new BasicDataSource(); LoaderScope
loaders = new LoaderScope(dataSource, loaderMode)) {
- dataSource.setDriverClassName(driverClass.getName());
- dataSource.setUrl(URL);
- final Driver driver = DriverFactory.createDriver(dataSource);
- assertSame(driverClass, driver.getClass());
- assertTrue(INITIALIZED_CLASSES.contains(driverClass));
- assertTrue(CONSTRUCTED_CLASSES.contains(driverClass));
- assertTrue(driver.acceptsURL(URL));
- loaders.assertUsed(driverClass.getName());
- }
- }
-
@Test
void testDriverInstanceTakesPrecedence() throws SQLException {
try (BasicDataSource dataSource = new BasicDataSource()) {
@@ -838,34 +838,34 @@ public class TestDriverFactory {
@ParameterizedTest
@EnumSource(LoaderMode.class)
- void testRejectNonDriverWithoutSideEffects(final LoaderMode loaderMode)
throws SQLException {
- // Class literals and getName() do not initialize these fixtures.
- final Class<?> nonDriverClass = loaderMode.nonDriverClass;
- assertNoSideEffects(nonDriverClass);
+ void testRejectNonDriverWithoutPublicConstructor(final LoaderMode
loaderMode) throws SQLException {
+ final Class<?> nonDriverClass =
NonDriverWithoutPublicConstructor.class;
+ assertFalse(INITIALIZED_CLASSES.contains(nonDriverClass));
try (BasicDataSource dataSource = new BasicDataSource(); LoaderScope
loaders = new LoaderScope(dataSource, loaderMode)) {
dataSource.setDriverClassName(nonDriverClass.getName());
dataSource.setUrl(URL);
final SQLException exception = assertThrows(SQLException.class, ()
-> DriverFactory.createDriver(dataSource));
assertConnectionFailure(exception);
- assertEquals("Cannot create JDBC driver of class '" +
nonDriverClass.getName() + "' for connect URL '" + URL + "'",
exception.getMessage());
assertInstanceOf(ClassCastException.class, exception.getCause());
- assertNoSideEffects(nonDriverClass);
+ assertFalse(INITIALIZED_CLASSES.contains(nonDriverClass), "A
non-driver must not be initialized");
loaders.assertUsed(nonDriverClass.getName());
}
}
@ParameterizedTest
@EnumSource(LoaderMode.class)
- void testRejectNonDriverWithoutPublicConstructor(final LoaderMode
loaderMode) throws SQLException {
- final Class<?> nonDriverClass =
NonDriverWithoutPublicConstructor.class;
- assertFalse(INITIALIZED_CLASSES.contains(nonDriverClass));
+ void testRejectNonDriverWithoutSideEffects(final LoaderMode loaderMode)
throws SQLException {
+ // Class literals and getName() do not initialize these fixtures.
+ final Class<?> nonDriverClass = loaderMode.nonDriverClass;
+ assertNoSideEffects(nonDriverClass);
try (BasicDataSource dataSource = new BasicDataSource(); LoaderScope
loaders = new LoaderScope(dataSource, loaderMode)) {
dataSource.setDriverClassName(nonDriverClass.getName());
dataSource.setUrl(URL);
final SQLException exception = assertThrows(SQLException.class, ()
-> DriverFactory.createDriver(dataSource));
assertConnectionFailure(exception);
+ assertEquals("Cannot create JDBC driver of class '" +
nonDriverClass.getName() + "' for connect URL '" + URL + "'",
exception.getMessage());
assertInstanceOf(ClassCastException.class, exception.getCause());
- assertFalse(INITIALIZED_CLASSES.contains(nonDriverClass), "A
non-driver must not be initialized");
+ assertNoSideEffects(nonDriverClass);
loaders.assertUsed(nonDriverClass.getName());
}
}
diff --git a/src/test/java/org/apache/commons/dbcp2/TestJdbcTimeouts.java
b/src/test/java/org/apache/commons/dbcp2/TestJdbcTimeouts.java
index 9c3ec92d..7f5c0319 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 {
+ /**
+ * 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)));
+ }
+
/**
* Creates a statement using one of the JDBC statement creation overloads.
*
@@ -94,6 +103,15 @@ class TestJdbcTimeouts {
}
}
+ /**
+ * 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)));
+ }
+
/**
* Creates a callable statement test double backed by a mutable query
timeout.
*
@@ -129,24 +147,6 @@ 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.
*
@@ -216,6 +216,27 @@ class TestJdbcTimeouts {
}
}
+ /**
+ * 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 {
+ try (BasicDataSource source = newDataSource(null)) {
+ try (Connection connection = source.getConnection()) {
+ final PreparedStatement statement = callable ?
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1");
+ statement.setQueryTimeout(7);
+ }
+ try (Connection connection = source.getConnection();
+ PreparedStatement statement = callable ?
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1")) {
+ assertEquals(1000, statement.getQueryTimeout());
+ }
+ }
+ }
+
/**
* Tests that DriverAdapterCPDS restores query timeouts between statement
borrowers.
*
@@ -361,6 +382,24 @@ 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 {
+ final CallableStatement raw = mock(CallableStatement.class);
+ when(raw.getQueryTimeout()).thenThrow(new
SQLFeatureNotSupportedException("Getter unavailable"));
+ try (PreparedStatement statement = callable ? new
DelegatingCallableStatement(null, raw) : new DelegatingPreparedStatement(null,
raw)) {
+ statement.setQueryTimeout(7);
+ verify(raw).setQueryTimeout(7);
+ verify(raw, never()).getQueryTimeout();
+ }
+ }
+
/**
* Tests that a statement is discarded when its original query timeout
cannot be restored.
*
@@ -388,87 +427,65 @@ 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.
+ * 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
- @ValueSource(booleans = {false, true})
- void testConnectionCloseRestoresUnclosedStatementTimeout(final boolean
callable) throws Exception {
- try (BasicDataSource source = newDataSource(null)) {
- try (Connection connection = source.getConnection()) {
- final PreparedStatement statement = callable ?
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1");
- statement.setQueryTimeout(7);
+ @MethodSource("changedDelegates")
+ void testPooledTimeoutFollowsReplacementDelegate(final boolean callable,
final boolean changeTimeout) throws Exception {
+ final Connection raw = mock(Connection.class);
+ final AtomicInteger originalTimeout = new AtomicInteger(5);
+ final AtomicInteger replacementTimeout = new AtomicInteger(9);
+ final CallableStatement original = mockStatement(originalTimeout);
+ final CallableStatement replacement =
mockStatement(replacementTimeout);
+ when(raw.prepareStatement("SELECT 1")).thenReturn(original);
+ when(raw.prepareCall("SELECT 1")).thenReturn(original);
+ try (PoolingConnection connection = new PoolingConnection(raw);
+ GenericKeyedObjectPool<PStmtKey, DelegatingPreparedStatement>
pool = new GenericKeyedObjectPool<>(connection)) {
+ connection.setStatementPool(pool);
+ try (DelegatingPreparedStatement borrowed =
(DelegatingPreparedStatement)
+ (callable ? connection.prepareCall("SELECT 1") :
connection.prepareStatement("SELECT 1"))) {
+ borrowed.setQueryTimeout(7);
+ borrowed.setDelegate(replacement);
+ if (changeTimeout) {
+ borrowed.setQueryTimeout(11);
+ }
}
- try (Connection connection = source.getConnection();
- PreparedStatement statement = callable ?
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1")) {
- assertEquals(1000, statement.getQueryTimeout());
+ assertEquals(9, replacementTimeout.get());
+ try (PreparedStatement borrowed = callable ?
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1")) {
+ assertEquals(9, borrowed.getQueryTimeout());
}
+ } finally {
+ original.close();
}
}
/**
- * Tests that an unchanged pooled statement does not access the driver
query timeout.
+ * 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 testUntouchedPooledStatementDoesNotReadOrWriteTimeout(final boolean
callable) throws Exception {
+ void testPooledTimeoutPreservedWhenReassigningSameDelegate(final boolean
callable) throws Exception {
final Connection raw = mock(Connection.class);
- final CallableStatement statement = mock(CallableStatement.class);
+ final AtomicInteger timeout = new AtomicInteger(5);
+ final CallableStatement statement = mockStatement(timeout);
when(raw.prepareStatement("SELECT 1")).thenReturn(statement);
when(raw.prepareCall("SELECT 1")).thenReturn(statement);
try (PoolingConnection connection = new PoolingConnection(raw);
GenericKeyedObjectPool<PStmtKey, DelegatingPreparedStatement>
pool = new GenericKeyedObjectPool<>(connection)) {
connection.setStatementPool(pool);
- for (int i = 0; i < 2; i++) {
- try (PreparedStatement borrowed = callable ?
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1")) {
- assertFalse(borrowed.isClosed());
- }
+ try (DelegatingPreparedStatement borrowed =
(DelegatingPreparedStatement)
+ (callable ? connection.prepareCall("SELECT 1") :
connection.prepareStatement("SELECT 1"))) {
+ borrowed.setQueryTimeout(7);
+ borrowed.setDelegate(statement);
}
- verify(statement, never()).getQueryTimeout();
- verify(statement, never()).setQueryTimeout(anyInt());
- }
- }
-
- /**
- * 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 {
- final CallableStatement raw = mock(CallableStatement.class);
- when(raw.getQueryTimeout()).thenThrow(new
SQLFeatureNotSupportedException("Getter unavailable"));
- try (PreparedStatement statement = callable ? new
DelegatingCallableStatement(null, raw) : new DelegatingPreparedStatement(null,
raw)) {
- statement.setQueryTimeout(7);
- verify(raw).setQueryTimeout(7);
- verify(raw, never()).getQueryTimeout();
+ assertEquals(5, timeout.get());
}
}
@@ -514,65 +531,48 @@ class TestJdbcTimeouts {
}
/**
- * Tests that timeout restoration uses the replacement delegate's original
value.
+ * Tests duration conversion to bounded JDBC timeout seconds.
*
- * @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.
+ * @param timeout the duration under test.
+ * @param expected the expected timeout passed to JDBC, in seconds.
*/
@ParameterizedTest
- @MethodSource("changedDelegates")
- void testPooledTimeoutFollowsReplacementDelegate(final boolean callable,
final boolean changeTimeout) throws Exception {
- final Connection raw = mock(Connection.class);
- final AtomicInteger originalTimeout = new AtomicInteger(5);
- final AtomicInteger replacementTimeout = new AtomicInteger(9);
- final CallableStatement original = mockStatement(originalTimeout);
- final CallableStatement replacement =
mockStatement(replacementTimeout);
- when(raw.prepareStatement("SELECT 1")).thenReturn(original);
- when(raw.prepareCall("SELECT 1")).thenReturn(original);
- try (PoolingConnection connection = new PoolingConnection(raw);
- GenericKeyedObjectPool<PStmtKey, DelegatingPreparedStatement>
pool = new GenericKeyedObjectPool<>(connection)) {
- connection.setStatementPool(pool);
- try (DelegatingPreparedStatement borrowed =
(DelegatingPreparedStatement)
- (callable ? connection.prepareCall("SELECT 1") :
connection.prepareStatement("SELECT 1"))) {
- borrowed.setQueryTimeout(7);
- borrowed.setDelegate(replacement);
- if (changeTimeout) {
- borrowed.setQueryTimeout(11);
- }
- }
- assertEquals(9, replacementTimeout.get());
- try (PreparedStatement borrowed = callable ?
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1")) {
- assertEquals(9, borrowed.getQueryTimeout());
- }
- } finally {
- original.close();
- }
+ @MethodSource("timeouts")
+ void testToJdbcSeconds(final Duration timeout, final int expected) {
+ assertEquals(expected, Utils.toJdbcSeconds(timeout));
}
/**
- * Tests that reassigning the same delegate retains the saved original
timeout.
+ * Tests that JDBC timeout conversion rejects a null duration.
+ */
+ @Test
+ void testToJdbcSecondsNull() {
+ assertThrows(NullPointerException.class, () ->
Utils.toJdbcSeconds(null));
+ }
+
+ /**
+ * 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 testPooledTimeoutPreservedWhenReassigningSameDelegate(final boolean
callable) throws Exception {
+ void testUntouchedPooledStatementDoesNotReadOrWriteTimeout(final boolean
callable) throws Exception {
final Connection raw = mock(Connection.class);
- final AtomicInteger timeout = new AtomicInteger(5);
- final CallableStatement statement = mockStatement(timeout);
+ final CallableStatement statement = mock(CallableStatement.class);
when(raw.prepareStatement("SELECT 1")).thenReturn(statement);
when(raw.prepareCall("SELECT 1")).thenReturn(statement);
try (PoolingConnection connection = new PoolingConnection(raw);
GenericKeyedObjectPool<PStmtKey, DelegatingPreparedStatement>
pool = new GenericKeyedObjectPool<>(connection)) {
connection.setStatementPool(pool);
- try (DelegatingPreparedStatement borrowed =
(DelegatingPreparedStatement)
- (callable ? connection.prepareCall("SELECT 1") :
connection.prepareStatement("SELECT 1"))) {
- borrowed.setQueryTimeout(7);
- borrowed.setDelegate(statement);
+ for (int i = 0; i < 2; i++) {
+ try (PreparedStatement borrowed = callable ?
connection.prepareCall("SELECT 1") : connection.prepareStatement("SELECT 1")) {
+ assertFalse(borrowed.isClosed());
+ }
}
- assertEquals(5, timeout.get());
+ verify(statement, never()).getQueryTimeout();
+ verify(statement, never()).setQueryTimeout(anyInt());
}
}
diff --git a/src/test/java/org/apache/commons/dbcp2/TestObjectNameWrapper.java
b/src/test/java/org/apache/commons/dbcp2/TestObjectNameWrapper.java
index 928950a0..aaa9b251 100644
--- a/src/test/java/org/apache/commons/dbcp2/TestObjectNameWrapper.java
+++ b/src/test/java/org/apache/commons/dbcp2/TestObjectNameWrapper.java
@@ -60,18 +60,6 @@ import org.junit.jupiter.params.provider.ValueSource;
*/
public class TestObjectNameWrapper {
- /**
- * Management interface for distinguishing registrations on different
servers.
- */
- public interface ValueMBean {
- /**
- * Gets the value identifying this registration.
- *
- * @return The value.
- */
- int getValue();
- }
-
/**
* Initializes a separate wrapper class with unavailable management
support, without changing the platform server or system properties.
*/
@@ -109,6 +97,18 @@ public class TestObjectNameWrapper {
}
}
+ /**
+ * Management interface for distinguishing registrations on different
servers.
+ */
+ public interface ValueMBean {
+ /**
+ * Gets the value identifying this registration.
+ *
+ * @return The value.
+ */
+ int getValue();
+ }
+
private static Method accessibleMethod(final Class<?> type, final String
name, final Class<?>... parameterTypes) throws NoSuchMethodException {
final Method method = type.getDeclaredMethod(name, parameterTypes);
method.setAccessible(true);
@@ -156,18 +156,18 @@ public class TestObjectNameWrapper {
return Stream.of(new SecurityException("Access denied"), new
NoClassDefFoundError("Missing dependency"), new AssertionError("Unexpected
failure"));
}
- private static Stream<Throwable> unregistrationFailures() {
- return Stream.of(new InstanceNotFoundException("Registration was
removed"),
- new MBeanRegistrationException(new Exception("Unregistration
callback failed")),
- new SecurityException("Unregistration denied"), new
NoClassDefFoundError("Missing dependency"));
- }
-
private static void unregisterIfPresent(final MBeanServer server, final
ObjectName name) throws Exception {
if (server.isRegistered(name)) {
server.unregisterMBean(name);
}
}
+ private static Stream<Throwable> unregistrationFailures() {
+ return Stream.of(new InstanceNotFoundException("Registration was
removed"),
+ new MBeanRegistrationException(new Exception("Unregistration
callback failed")),
+ new SecurityException("Unregistration denied"), new
NoClassDefFoundError("Missing dependency"));
+ }
+
@Test
void testDuplicateRegistrationPreservesExistingMBean() throws Exception {
final MBeanServer server = MBeanServerFactory.newMBeanServer();
diff --git a/src/test/java/org/apache/commons/dbcp2/TestPoolableConnection.java
b/src/test/java/org/apache/commons/dbcp2/TestPoolableConnection.java
index 2f84e520..56ebde5b 100644
--- a/src/test/java/org/apache/commons/dbcp2/TestPoolableConnection.java
+++ b/src/test/java/org/apache/commons/dbcp2/TestPoolableConnection.java
@@ -57,8 +57,6 @@ import org.mockito.InOrder;
*/
public class TestPoolableConnection {
- private GenericObjectPool<PoolableConnection> pool;
-
private static Stream<Arguments> fastFailValidationArguments() {
return Stream.of(false, true).flatMap(fastFail -> Stream.of(null, "",
"SELECT 1").map(sql -> Arguments.of(fastFail, sql)));
}
@@ -101,6 +99,8 @@ public class TestPoolableConnection {
.flatMap(timeout -> Stream.of(null, "").map(sql ->
Arguments.of(sql, timeout.get()[0], timeout.get()[1])));
}
+ private GenericObjectPool<PoolableConnection> pool;
+
@BeforeEach
public void setUp() throws Exception {
final PoolableConnectionFactory factory = new
PoolableConnectionFactory(
diff --git a/src/test/java/org/apache/commons/dbcp2/TestPoolingDataSource.java
b/src/test/java/org/apache/commons/dbcp2/TestPoolingDataSource.java
index e6c751e5..0611cc12 100644
--- a/src/test/java/org/apache/commons/dbcp2/TestPoolingDataSource.java
+++ b/src/test/java/org/apache/commons/dbcp2/TestPoolingDataSource.java
@@ -46,10 +46,6 @@ import org.junit.jupiter.params.provider.ValueSource;
*/
public class TestPoolingDataSource extends TestConnectionPool {
- protected PoolingDataSource<PoolableConnection> ds;
-
- private GenericObjectPool<PoolableConnection> pool;
-
private static void closeWithStatementFailure(final
DelegatingConnection<?> connection) throws SQLException {
try (TesterStatement physicalStatement = new
TesterStatement(connection);
DelegatingStatement statement = new
DelegatingStatement(connection, physicalStatement)) {
@@ -62,6 +58,10 @@ public class TestPoolingDataSource extends
TestConnectionPool {
}
}
+ protected PoolingDataSource<PoolableConnection> ds;
+
+ private GenericObjectPool<PoolableConnection> pool;
+
@Override
protected Connection getConnection() throws Exception {
return ds.getConnection();
@@ -144,6 +144,31 @@ public class TestPoolingDataSource extends
TestConnectionPool {
}
}
+ @Test
+ void testClose() throws Exception {
+ final Properties properties = new Properties();
+ properties.setProperty(Constants.KEY_USER, "userName");
+ properties.setProperty(Constants.KEY_PASSWORD, "password");
+ final PoolableConnectionFactory f = new PoolableConnectionFactory(
+ new DriverConnectionFactory(new TesterDriver(),
"jdbc:apache:commons:testdriver", properties), null);
+ f.setValidationQuery("SELECT DUMMY FROM DUAL");
+ f.setDefaultReadOnly(Boolean.TRUE);
+ f.setDefaultAutoCommit(Boolean.TRUE);
+ final GenericObjectPool<PoolableConnection> p = new
GenericObjectPool<>(f);
+ p.setMaxTotal(getMaxTotal());
+ p.setMaxWait(getMaxWaitDuration());
+
+ try (PoolingDataSource<PoolableConnection> dataSource = new
PoolingDataSource<>(p)) {
+ final Connection connection = dataSource.getConnection();
+ assertNotNull(connection);
+ connection.close();
+ }
+
+ assertTrue(p.isClosed());
+ assertEquals(0, p.getNumIdle());
+ assertEquals(0, p.getNumActive());
+ }
+
@ParameterizedTest
@ValueSource(booleans = {false, true})
void testCloseClearsDelegateAfterStatementFailure(final boolean allowed)
throws Exception {
@@ -200,31 +225,6 @@ public class TestPoolingDataSource extends
TestConnectionPool {
}
}
- @Test
- void testClose() throws Exception {
- final Properties properties = new Properties();
- properties.setProperty(Constants.KEY_USER, "userName");
- properties.setProperty(Constants.KEY_PASSWORD, "password");
- final PoolableConnectionFactory f = new PoolableConnectionFactory(
- new DriverConnectionFactory(new TesterDriver(),
"jdbc:apache:commons:testdriver", properties), null);
- f.setValidationQuery("SELECT DUMMY FROM DUAL");
- f.setDefaultReadOnly(Boolean.TRUE);
- f.setDefaultAutoCommit(Boolean.TRUE);
- final GenericObjectPool<PoolableConnection> p = new
GenericObjectPool<>(f);
- p.setMaxTotal(getMaxTotal());
- p.setMaxWait(getMaxWaitDuration());
-
- try (PoolingDataSource<PoolableConnection> dataSource = new
PoolingDataSource<>(p)) {
- final Connection connection = dataSource.getConnection();
- assertNotNull(connection);
- connection.close();
- }
-
- assertTrue(p.isClosed());
- assertEquals(0, p.getNumIdle());
- assertEquals(0, p.getNumActive());
- }
-
/**
* DBCP-412
* Verify that omitting factory.setPool(pool) when setting up PDS does not
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 8621a207..1b8a8d5d 100644
---
a/src/test/java/org/apache/commons/dbcp2/cpdsadapter/TestDriverAdapterCPDSReference.java
+++
b/src/test/java/org/apache/commons/dbcp2/cpdsadapter/TestDriverAdapterCPDSReference.java
@@ -83,6 +83,57 @@ class TestDriverAdapterCPDSReference {
}
}
+ /**
+ * 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),
+ Duration.ofSeconds(Long.MAX_VALUE, 999_999_999)),
+ LongStream.of(-1, -2, -59, -60, -61, -3599, -3600, -3601,
Long.MIN_VALUE)
+ .boxed().flatMap(seconds -> IntStream.of(0, 1,
500_000_000, 999_999_999)
+ .mapToObj(nanos -> Duration.ofSeconds(seconds,
nanos))))
+ .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)),
+ Arguments.of("PT-0.1S", Duration.ofMillis(-100)),
+ Arguments.of("PT-00.500000000S", Duration.ofMillis(-500)),
+ Arguments.of("PT-000.999999999S",
Duration.ofNanos(-999_999_999)),
+ Arguments.of("+PT-0,1S", Duration.ofMillis(-100)),
+ Arguments.of("pt-0,000000001s", Duration.ofNanos(-1)),
+ Arguments.of("-PT-0.000000001S", Duration.ofNanos(1)),
+ Arguments.of("-pt-00,1s", Duration.ofMillis(100)),
+ Arguments.of("PT-0.S", Duration.ZERO),
+ Arguments.of("PT-0,S", Duration.ZERO),
+ Arguments.of("PT-0.000000000S", Duration.ZERO),
+ Arguments.of("PT-0S", Duration.ZERO),
+ Arguments.of("PT0.000000001S", Duration.ofNanos(1)),
+ Arguments.of("-PT0.000000001S", Duration.ofNanos(-1)),
+ Arguments.of("PT-1M-0.000000001S", Duration.ofSeconds(-60,
-1)),
+ Arguments.of("PT1M-0.5S", Duration.ofMillis(59_500)),
+ Arguments.of("-PT1M-0.5S", Duration.ofMillis(-59_500)),
+ Arguments.of("PT-1H-0.1S", Duration.ofMillis(-3_600_100)),
+ Arguments.of("PT1H-1M-0.1S", Duration.ofMillis(3_539_900)),
+ Arguments.of("P-1DT2H-3M-0.1S",
Duration.ofMillis(-79_380_100)),
+ Arguments.of("-P-1DT2H-3M-0.1S",
Duration.ofMillis(79_380_100)),
+ Arguments.of("PT2562047788015215H30M-0.000000001S",
Duration.ofSeconds(Long.MAX_VALUE - 8, 999_999_999)),
+ Arguments.of("-PT2562047788015215H30M-0.000000001S",
Duration.ofSeconds(Long.MIN_VALUE + 8, 1)),
+ Arguments.of("PT-2562047788015215H-30M-0.000000001S",
Duration.ofSeconds(Long.MIN_VALUE + 7, 999_999_999)),
+ Arguments.of("PT-9223372036854775808S",
Duration.ofSeconds(Long.MIN_VALUE)),
+ Arguments.of("PT-9223372036854775807.999999999S",
Duration.ofSeconds(Long.MIN_VALUE, 1)),
+ Arguments.of("PT9223372036854775807.999999999S",
Duration.ofSeconds(Long.MAX_VALUE, 999_999_999)));
+ }
+
private static DriverAdapterCPDS newDataSource() throws Exception {
final DriverAdapterCPDS source = new DriverAdapterCPDS();
source.setDriver(TesterDriver.class.getName());
@@ -134,6 +185,49 @@ class TestDriverAdapterCPDSReference {
assertCanConnect(resolved);
}
+ /**
+ * 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 {
+ final DriverAdapterCPDS source = newDataSource();
+ source.setDurationBetweenEvictionRuns(duration);
+ source.setMinEvictableIdleDuration(duration);
+ final Reference reference = source.getReference();
+ if (modernOnly) {
+ removeAddress(reference, "timeBetweenEvictionRunsMillis");
+ removeAddress(reference, "minEvictableIdleTimeMillis");
+ }
+ final DriverAdapterCPDS restored = resolve(reference);
+ assertEquals(duration, restored.getDurationBetweenEvictionRuns());
+ 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 {
+ final Reference reference = new
Reference(DriverAdapterCPDS.class.getName(), DriverAdapterCPDS.class.getName(),
null);
+ reference.add(new StringRefAddr("durationBetweenEvictionRuns", text));
+ reference.add(new StringRefAddr("minEvictableIdleDuration", text));
+ reference.add(new StringRefAddr("timeBetweenEvictionRunsMillis", "0"));
+ reference.add(new StringRefAddr("minEvictableIdleTimeMillis", "0"));
+ final DriverAdapterCPDS restored = resolve(reference);
+ assertEquals(expected, restored.getDurationBetweenEvictionRuns());
+ assertEquals(expected, restored.getMinEvictableIdleDuration());
+ }
+
@Test
void testExportCanChangeAfterConnectionUse() throws Exception {
final DriverAdapterCPDS source = newDataSource();
@@ -229,6 +323,41 @@ class TestDriverAdapterCPDSReference {
assertCanConnect(factory);
}
+ /**
+ * 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"})
+ void testInvalidDurationReference(final String text) {
+ for (final String key : new String[] {"durationBetweenEvictionRuns",
"minEvictableIdleDuration"}) {
+ final Reference reference = new
Reference(DriverAdapterCPDS.class.getName(), DriverAdapterCPDS.class.getName(),
null);
+ reference.add(new StringRefAddr(key, text));
+ reference.add(new StringRefAddr("timeBetweenEvictionRunsMillis",
"0"));
+ reference.add(new StringRefAddr("minEvictableIdleTimeMillis",
"0"));
+ assertThrows(DateTimeParseException.class, () ->
resolve(reference));
+ }
+ }
+
+ /**
+ * 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 {
+ final Reference reference = new
Reference(DriverAdapterCPDS.class.getName(), DriverAdapterCPDS.class.getName(),
null);
+ reference.add(new StringRefAddr("timeBetweenEvictionRunsMillis",
Long.toString(millis)));
+ reference.add(new StringRefAddr("minEvictableIdleTimeMillis",
Long.toString(millis)));
+ final DriverAdapterCPDS restored = resolve(reference);
+ assertEquals(Duration.ofMillis(millis),
restored.getDurationBetweenEvictionRuns());
+ assertEquals(Duration.ofMillis(millis),
restored.getMinEvictableIdleDuration());
+ }
+
@Test
void testLegacyReferenceRetainsPasswordExport() throws Exception {
final Reference reference = newDataSource().getReference();
@@ -265,6 +394,40 @@ class TestDriverAdapterCPDSReference {
assertCanConnect(source);
}
+ /**
+ * 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);
+ reference.add(new StringRefAddr("durationBetweenEvictionRuns",
"PT0.001S"));
+ reference.add(new StringRefAddr("minEvictableIdleDuration", "PT720H"));
+ reference.add(new StringRefAddr("timeBetweenEvictionRunsMillis",
"invalid"));
+ reference.add(new StringRefAddr("minEvictableIdleTimeMillis",
"invalid"));
+ final DriverAdapterCPDS restored = resolve(reference);
+ assertEquals(Duration.ofMillis(1),
restored.getDurationBetweenEvictionRuns());
+ 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);
+ reference.add(new StringRefAddr("durationBetweenEvictionRuns", null));
+ reference.add(new StringRefAddr("minEvictableIdleDuration", null));
+ reference.add(new StringRefAddr("timeBetweenEvictionRunsMillis",
"2592000000"));
+ reference.add(new StringRefAddr("minEvictableIdleTimeMillis",
"2592000000"));
+ final DriverAdapterCPDS restored = resolve(reference);
+ assertEquals(Duration.ofDays(30),
restored.getDurationBetweenEvictionRuns());
+ assertEquals(Duration.ofDays(30),
restored.getMinEvictableIdleDuration());
+ }
+
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testPasswordProvisioningBeforePoolInitialization(final boolean
useCharArray) throws Exception {
@@ -366,167 +529,4 @@ 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),
- Duration.ofSeconds(Long.MAX_VALUE, 999_999_999)),
- LongStream.of(-1, -2, -59, -60, -61, -3599, -3600, -3601,
Long.MIN_VALUE)
- .boxed().flatMap(seconds -> IntStream.of(0, 1,
500_000_000, 999_999_999)
- .mapToObj(nanos -> Duration.ofSeconds(seconds,
nanos))))
- .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)),
- Arguments.of("PT-0.1S", Duration.ofMillis(-100)),
- Arguments.of("PT-00.500000000S", Duration.ofMillis(-500)),
- Arguments.of("PT-000.999999999S",
Duration.ofNanos(-999_999_999)),
- Arguments.of("+PT-0,1S", Duration.ofMillis(-100)),
- Arguments.of("pt-0,000000001s", Duration.ofNanos(-1)),
- Arguments.of("-PT-0.000000001S", Duration.ofNanos(1)),
- Arguments.of("-pt-00,1s", Duration.ofMillis(100)),
- Arguments.of("PT-0.S", Duration.ZERO),
- Arguments.of("PT-0,S", Duration.ZERO),
- Arguments.of("PT-0.000000000S", Duration.ZERO),
- Arguments.of("PT-0S", Duration.ZERO),
- Arguments.of("PT0.000000001S", Duration.ofNanos(1)),
- Arguments.of("-PT0.000000001S", Duration.ofNanos(-1)),
- Arguments.of("PT-1M-0.000000001S", Duration.ofSeconds(-60,
-1)),
- Arguments.of("PT1M-0.5S", Duration.ofMillis(59_500)),
- Arguments.of("-PT1M-0.5S", Duration.ofMillis(-59_500)),
- Arguments.of("PT-1H-0.1S", Duration.ofMillis(-3_600_100)),
- Arguments.of("PT1H-1M-0.1S", Duration.ofMillis(3_539_900)),
- Arguments.of("P-1DT2H-3M-0.1S",
Duration.ofMillis(-79_380_100)),
- Arguments.of("-P-1DT2H-3M-0.1S",
Duration.ofMillis(79_380_100)),
- Arguments.of("PT2562047788015215H30M-0.000000001S",
Duration.ofSeconds(Long.MAX_VALUE - 8, 999_999_999)),
- Arguments.of("-PT2562047788015215H30M-0.000000001S",
Duration.ofSeconds(Long.MIN_VALUE + 8, 1)),
- Arguments.of("PT-2562047788015215H-30M-0.000000001S",
Duration.ofSeconds(Long.MIN_VALUE + 7, 999_999_999)),
- Arguments.of("PT-9223372036854775808S",
Duration.ofSeconds(Long.MIN_VALUE)),
- Arguments.of("PT-9223372036854775807.999999999S",
Duration.ofSeconds(Long.MIN_VALUE, 1)),
- 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 {
- final DriverAdapterCPDS source = newDataSource();
- source.setDurationBetweenEvictionRuns(duration);
- source.setMinEvictableIdleDuration(duration);
- final Reference reference = source.getReference();
- if (modernOnly) {
- removeAddress(reference, "timeBetweenEvictionRunsMillis");
- removeAddress(reference, "minEvictableIdleTimeMillis");
- }
- final DriverAdapterCPDS restored = resolve(reference);
- assertEquals(duration, restored.getDurationBetweenEvictionRuns());
- 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 {
- final Reference reference = new
Reference(DriverAdapterCPDS.class.getName(), DriverAdapterCPDS.class.getName(),
null);
- reference.add(new StringRefAddr("durationBetweenEvictionRuns", text));
- reference.add(new StringRefAddr("minEvictableIdleDuration", text));
- reference.add(new StringRefAddr("timeBetweenEvictionRunsMillis", "0"));
- reference.add(new StringRefAddr("minEvictableIdleTimeMillis", "0"));
- final DriverAdapterCPDS restored = resolve(reference);
- assertEquals(expected, restored.getDurationBetweenEvictionRuns());
- 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"})
- void testInvalidDurationReference(final String text) {
- for (final String key : new String[] {"durationBetweenEvictionRuns",
"minEvictableIdleDuration"}) {
- final Reference reference = new
Reference(DriverAdapterCPDS.class.getName(), DriverAdapterCPDS.class.getName(),
null);
- reference.add(new StringRefAddr(key, text));
- reference.add(new StringRefAddr("timeBetweenEvictionRunsMillis",
"0"));
- reference.add(new StringRefAddr("minEvictableIdleTimeMillis",
"0"));
- assertThrows(DateTimeParseException.class, () ->
resolve(reference));
- }
- }
-
- /**
- * 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 {
- final Reference reference = new
Reference(DriverAdapterCPDS.class.getName(), DriverAdapterCPDS.class.getName(),
null);
- reference.add(new StringRefAddr("timeBetweenEvictionRunsMillis",
Long.toString(millis)));
- reference.add(new StringRefAddr("minEvictableIdleTimeMillis",
Long.toString(millis)));
- final DriverAdapterCPDS restored = resolve(reference);
- assertEquals(Duration.ofMillis(millis),
restored.getDurationBetweenEvictionRuns());
- 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);
- reference.add(new StringRefAddr("durationBetweenEvictionRuns",
"PT0.001S"));
- reference.add(new StringRefAddr("minEvictableIdleDuration", "PT720H"));
- reference.add(new StringRefAddr("timeBetweenEvictionRunsMillis",
"invalid"));
- reference.add(new StringRefAddr("minEvictableIdleTimeMillis",
"invalid"));
- final DriverAdapterCPDS restored = resolve(reference);
- assertEquals(Duration.ofMillis(1),
restored.getDurationBetweenEvictionRuns());
- 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);
- reference.add(new StringRefAddr("durationBetweenEvictionRuns", null));
- reference.add(new StringRefAddr("minEvictableIdleDuration", null));
- reference.add(new StringRefAddr("timeBetweenEvictionRunsMillis",
"2592000000"));
- reference.add(new StringRefAddr("minEvictableIdleTimeMillis",
"2592000000"));
- final DriverAdapterCPDS restored = resolve(reference);
- assertEquals(Duration.ofDays(30),
restored.getDurationBetweenEvictionRuns());
- assertEquals(Duration.ofDays(30),
restored.getMinEvictableIdleDuration());
- }
-
}
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 2ad8f4e4..6f4db3c8 100644
--- a/src/test/java/org/apache/commons/dbcp2/datasources/TestLoginTimeout.java
+++ b/src/test/java/org/apache/commons/dbcp2/datasources/TestLoginTimeout.java
@@ -73,23 +73,6 @@ import org.junit.jupiter.params.provider.ValueSource;
/** Tests physical connection login timeouts, including configuration after
pool initialization. */
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);
-
when(context.lookup("timeoutTest")).thenReturn(environment.get("test.cpds"));
- return context;
- }
- }
-
private static final class RecordingCpds extends
ConnectionPoolDataSourceProxy {
private int timeout = 9;
private final List<Integer> attempts = new ArrayList<>();
@@ -237,34 +220,64 @@ 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);
+
when(context.lookup("timeoutTest")).thenReturn(environment.get("test.cpds"));
+ return context;
+ }
+ }
+
/**
- * Supplies bounded and unbounded timeout settings for interruption tests.
+ * Configures a data source to obtain its provider directly or through
JNDI and retain no idle connections.
*
- * @return an unset timeout, zero, and a positive sub-second timeout.
+ * @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.
*/
- static Stream<Duration> interruptedTimeouts() {
- return Stream.of(null, Duration.ZERO, Duration.ofMillis(100));
+ 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());
+ environment.put("test.cpds", provider);
+ source.setJndiEnvironment(environment);
+ source.setDataSourceName("timeoutTest");
+ } else {
+ source.setConnectionPoolDataSource(provider);
+ }
+ source.setDefaultMaxIdle(0);
}
/**
- * Supplies pool types and initial timeout settings for serialization
tests.
+ * Deserializes a data source from its serialized representation.
*
- * @return shared-pool and configured-timeout flag combinations.
+ * @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.
*/
- static Stream<Arguments> serializationTimeouts() {
- return Stream.of(false, true).flatMap(shared -> Stream.of(false,
true).map(configured -> Arguments.of(shared, configured)));
+ private static InstanceKeyDataSource deserialize(final byte[] bytes)
throws IOException, ClassNotFoundException {
+ try (ObjectInputStream input = new ObjectInputStream(new
ByteArrayInputStream(bytes))) {
+ return (InstanceKeyDataSource) input.readObject();
+ }
}
/**
- * Supplies pool types, provider lookup modes, and timeouts for
serialization before provider configuration.
+ * Supplies bounded and unbounded timeout settings for interruption tests.
*
- * @return configuration combinations and the timeout expected by the
provider after deserialization.
+ * @return an unset timeout, zero, and a positive sub-second timeout.
*/
- 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]))));
+ static Stream<Duration> interruptedTimeouts() {
+ return Stream.of(null, Duration.ZERO, Duration.ofMillis(100));
}
/**
@@ -297,40 +310,6 @@ class TestLoginTimeout {
return provider;
}
- /**
- * 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());
- environment.put("test.cpds", provider);
- source.setJndiEnvironment(environment);
- source.setDataSourceName("timeoutTest");
- } else {
- 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.
*
@@ -345,6 +324,15 @@ class TestLoginTimeout {
return source;
}
+ /**
+ * 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)));
+ }
+
/**
* Serializes a data source without closing it or changing its
registration.
*
@@ -360,6 +348,27 @@ class TestLoginTimeout {
return bytes.toByteArray();
}
+ /**
+ * 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"));
+ }
+
+ /**
+ * 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]))));
+ }
+
/**
* Tests that a connection failure restores the provider's previous login
timeout.
*
@@ -397,6 +406,47 @@ class TestLoginTimeout {
assertEquals(Arrays.asList(restoreFailure),
Arrays.asList(failure.getSuppressed()));
}
+ /**
+ * 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 {
+ final SerializableCpds provider = new SerializableCpds();
+ try (InstanceKeyDataSource source = newDataSource(shared, false,
provider)) {
+ if (configured) {
+ source.setLoginTimeout(Duration.ofSeconds(5));
+ }
+ try (Connection connection = source.getConnection()) {
+ assertFalse(connection.isClosed());
+ }
+ try (InstanceKeyDataSource restored =
deserialize(serialize(source))) {
+ assertEquals(source.getLoginTimeoutDuration(),
restored.getLoginTimeoutDuration());
+ restored.setLoginTimeout(Duration.ofSeconds(3));
+ assertEquals(Duration.ofSeconds(3),
source.getLoginTimeoutDuration());
+ provider.attempts.clear();
+ try (Connection connection = restored.getConnection()) {
+ assertFalse(connection.isClosed());
+ }
+ assertFalse(provider.attempts.isEmpty());
+ provider.attempts.forEach(value -> assertEquals(3,
value.intValue()));
+ source.setLoginTimeout(Duration.ofSeconds(7));
+ assertEquals(Duration.ofSeconds(7),
restored.getLoginTimeoutDuration());
+ provider.attempts.clear();
+ try (Connection connection = restored.getConnection()) {
+ assertFalse(connection.isClosed());
+ }
+ assertFalse(provider.attempts.isEmpty());
+ provider.attempts.forEach(value -> assertEquals(7,
value.intValue()));
+ assertEquals(9, provider.getLoginTimeout());
+ }
+ }
+ }
+
/**
* Tests that an unchanged login timeout avoids a provider setter call.
*
@@ -465,54 +515,238 @@ class TestLoginTimeout {
}
/**
- * Tests that a restoration failure closes the acquired connection and
retains a subsequent close failure.
+ * Tests that provider-enforced login timeouts apply before and after pool
initialization.
*
- * @throws SQLException if JDBC setup, an operation, or cleanup
unexpectedly fails.
+ * @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.
*/
- @Test
- void testRestoreFailureClosesConnectionAndSuppressesCloseFailure() throws
SQLException {
- final ConnectionPoolDataSource provider =
mock(ConnectionPoolDataSource.class);
- final PooledConnection connection = mock(PooledConnection.class);
- final SQLException restoreFailure = new SQLException("Restore failed");
- final SQLException closeFailure = new SQLException("Close failed");
- when(provider.getLoginTimeout()).thenReturn(9);
- when(provider.getPooledConnection()).thenReturn(connection);
- doThrow(restoreFailure).when(provider).setLoginTimeout(9);
- doThrow(closeFailure).when(connection).close();
- assertSame(restoreFailure, assertThrows(SQLException.class, () ->
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
- null, null, Duration.ofSeconds(1))));
- verify(connection).close();
- assertEquals(Arrays.asList(closeFailure),
Arrays.asList(restoreFailure.getSuppressed()));
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testProviderEnforcesTimeoutForInitialAndLaterConnections(final
boolean shared) throws Exception {
+ final RecordingCpds provider = new RecordingCpds();
+ provider.enforceTimeout = true;
+ try (InstanceKeyDataSource source = newDataSource(shared, false,
provider)) {
+ source.setLoginTimeout(Duration.ofMillis(100));
+ assertThrows(SQLException.class, source::getConnection);
+ assertEquals(9, provider.getLoginTimeout());
+ }
+ try (InstanceKeyDataSource source = newDataSource(shared, false,
provider)) {
+ source.setLoginTimeout(5);
+ try (Connection connection = source.getConnection()) {
+ assertFalse(connection.isClosed());
+ }
+ source.setLoginTimeout(Duration.ofMillis(100));
+ assertThrows(SQLException.class, source::getConnection);
+ assertEquals(9, provider.getLoginTimeout());
+ }
}
/**
- * Tests timeout restoration when the provider setter changes its state
before failing.
+ * 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.
*/
- @Test
- void testSetterFailureRestoresProviderTimeout() throws SQLException {
- final AtomicInteger timeout = new AtomicInteger(9);
- final ConnectionPoolDataSource provider = mockProvider(timeout);
- final SQLException failure = new SQLException("Cannot apply timeout");
- doAnswer(invocation -> {
- timeout.set(1);
- throw failure;
- }).when(provider).setLoginTimeout(1);
- assertSame(failure, assertThrows(SQLException.class, () ->
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
- null, null, Duration.ofSeconds(1))));
- assertEquals(9, timeout.get());
- verify(provider, never()).getPooledConnection();
+ @ParameterizedTest
+ @MethodSource("interruptedTimeouts")
+ void testProviderLockPreservesInterruption(final Duration timeout) throws
SQLException {
+ final ConnectionPoolDataSource provider =
mock(ConnectionPoolDataSource.class);
+ Thread.currentThread().interrupt();
+ try {
+ final SQLException failure = assertThrows(SQLException.class, ()
-> ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+ null, null, timeout));
+ assertInstanceOf(InterruptedException.class, failure.getCause());
+ assertTrue(Thread.currentThread().isInterrupted());
+ verify(provider, never()).getPooledConnection();
+ verify(provider, never()).setLoginTimeout(anyInt());
+ } finally {
+ Thread.interrupted();
+ }
}
/**
- * Tests that temporary timeout overrides exclude overlapping attempts
through the same provider.
+ * Tests that each provider failure path releases the lock for a
subsequent attempt from another thread.
*
- * @param secondUsesProviderDefault whether the second attempt leaves the
provider timeout unconfigured.
+ * @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(booleans = {false, true})
+ @ValueSource(strings = {"read", "set", "connect", "restore"})
+ void testProviderLockReleasedAfterFailure(final String phase) throws
Exception {
+ final ConnectionPoolDataSource provider =
mock(ConnectionPoolDataSource.class);
+ final AtomicInteger timeout = new AtomicInteger(9);
+ final AtomicBoolean failOnce = new AtomicBoolean(true);
+ final SQLException failure = new SQLException("Provider failure during
" + phase);
+ when(provider.getLoginTimeout()).thenAnswer(invocation -> {
+ if ("read".equals(phase) && failOnce.getAndSet(false)) {
+ throw failure;
+ }
+ return timeout.get();
+ });
+ doAnswer(invocation -> {
+ final int seconds = invocation.getArgument(0);
+ timeout.set(seconds);
+ if (("set".equals(phase) && seconds == 1 ||
"restore".equals(phase) && seconds == 9) && failOnce.getAndSet(false)) {
+ throw failure;
+ }
+ return null;
+ }).when(provider).setLoginTimeout(anyInt());
+ when(provider.getPooledConnection()).thenAnswer(invocation -> {
+ if ("connect".equals(phase) && failOnce.getAndSet(false)) {
+ throw failure;
+ }
+ return mock(PooledConnection.class);
+ });
+ assertSame(failure, assertThrows(SQLException.class, () ->
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+ null, null, Duration.ofSeconds(1))));
+ assertEquals(9, timeout.get());
+ // A different thread must be able to acquire the provider lock after
every failure path.
+ final ExecutorService executor = Executors.newSingleThreadExecutor();
+ try {
+ final Future<PooledConnection> next = executor.submit(() ->
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+ null, null, Duration.ofSeconds(2)));
+ final PooledConnection connection = next.get(5, TimeUnit.SECONDS);
+ assertNotNull(connection);
+ connection.close();
+ assertEquals(9, timeout.get());
+ } finally {
+ executor.shutdownNow();
+ assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+
+ /**
+ * 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 {
+ final SerializableCpds firstProvider = new SerializableCpds();
+ final SerializableCpds secondProvider = sameProvider ? firstProvider :
new SerializableCpds();
+ // Equal but distinct providers must not share a lock. A changing hash
must not bypass a provider's own lock.
+ firstProvider.equalToOtherProviders = !sameProvider;
+ secondProvider.equalToOtherProviders = !sameProvider;
+ firstProvider.entered = new CountDownLatch(1);
+ firstProvider.release = new CountDownLatch(1);
+ final ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ final Future<PooledConnection> first = executor.submit(() ->
ConnectionPoolDataSourceUtils.getPooledConnection(firstProvider,
+ null, null, Duration.ofSeconds(1)));
+ assertTrue(firstProvider.entered.await(10, TimeUnit.SECONDS));
+ final Future<PooledConnection> second = executor.submit(() ->
ConnectionPoolDataSourceUtils.getPooledConnection(secondProvider,
+ null, null, Duration.ofSeconds(2)));
+ if (sameProvider) {
+ assertThrows(TimeoutException.class, () -> second.get(100,
TimeUnit.MILLISECONDS));
+ } else {
+ assertNotNull(second.get(5, TimeUnit.SECONDS));
+ assertEquals(Collections.singletonList(2),
secondProvider.attempts);
+ }
+ firstProvider.release.countDown();
+ first.get(10, TimeUnit.SECONDS).close();
+ second.get(10, TimeUnit.SECONDS).close();
+ assertEquals(sameProvider ? Arrays.asList(1, 2) :
Collections.singletonList(1), firstProvider.attempts);
+ assertEquals(9, firstProvider.getLoginTimeout());
+ assertEquals(9, secondProvider.getLoginTimeout());
+ } finally {
+ firstProvider.release.countDown();
+ executor.shutdownNow();
+ assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+
+ /**
+ * 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 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);
+ final SQLException failure = new SQLException("Driver failed");
+ when(provider.getLoginTimeout()).thenReturn(9);
+ when(provider.getPooledConnection()).thenThrow(failure);
+ doThrow(failure).when(provider).setLoginTimeout(9);
+ assertSame(failure, assertThrows(SQLException.class, () ->
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+ null, null, Duration.ofSeconds(1))));
+ assertEquals(0, failure.getSuppressed().length);
+ }
+
+ /**
+ * 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);
+ final PooledConnection connection = mock(PooledConnection.class);
+ final SQLException restoreFailure = new SQLException("Restore failed");
+ final SQLException closeFailure = new SQLException("Close failed");
+ when(provider.getLoginTimeout()).thenReturn(9);
+ when(provider.getPooledConnection()).thenReturn(connection);
+ doThrow(restoreFailure).when(provider).setLoginTimeout(9);
+ doThrow(closeFailure).when(connection).close();
+ assertSame(restoreFailure, assertThrows(SQLException.class, () ->
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+ null, null, Duration.ofSeconds(1))));
+ verify(connection).close();
+ 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);
+ final ConnectionPoolDataSource provider = mockProvider(timeout);
+ final SQLException failure = new SQLException("Cannot apply timeout");
+ doAnswer(invocation -> {
+ timeout.set(1);
+ throw failure;
+ }).when(provider).setLoginTimeout(1);
+ assertSame(failure, assertThrows(SQLException.class, () ->
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
+ null, null, Duration.ofSeconds(1))));
+ assertEquals(9, timeout.get());
+ 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 {
final AtomicInteger timeout = new AtomicInteger(9);
final ConnectionPoolDataSource provider = mockProvider(timeout);
@@ -553,47 +787,6 @@ 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);
- ConnectionPoolDataSourceUtils.getPooledConnection(provider, null,
null, null);
- verify(provider).getPooledConnection();
- verify(provider, never()).getLoginTimeout();
- 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 {
- final RecordingCpds provider = new RecordingCpds();
- try (InstanceKeyDataSource source = newDataSource(shared, false,
provider);
- Connection connection = source.getConnection()) {
- assertFalse(connection.isClosed());
- assertFalse(provider.attempts.isEmpty());
- provider.attempts.forEach(value -> assertEquals(9,
value.intValue()));
- }
- }
-
- /**
- * 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.
*
@@ -612,111 +805,34 @@ class TestLoginTimeout {
}
/**
- * Tests that reusing the same driver exception for connection and
restoration failures avoids self-suppression.
+ * 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 testRepeatedDriverExceptionDoesNotSuppressItself() throws
SQLException {
+ void testUnconfiguredTimeoutDoesNotCallProviderTimeoutMethods() throws
SQLException {
final ConnectionPoolDataSource provider =
mock(ConnectionPoolDataSource.class);
- final SQLException failure = new SQLException("Driver failed");
- when(provider.getLoginTimeout()).thenReturn(9);
- when(provider.getPooledConnection()).thenThrow(failure);
- doThrow(failure).when(provider).setLoginTimeout(9);
- assertSame(failure, assertThrows(SQLException.class, () ->
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
- null, null, Duration.ofSeconds(1))));
- assertEquals(0, failure.getSuppressed().length);
+ ConnectionPoolDataSourceUtils.getPooledConnection(provider, null,
null, null);
+ verify(provider).getPooledConnection();
+ verify(provider, never()).getLoginTimeout();
+ verify(provider, never()).setLoginTimeout(anyInt());
}
/**
- * Tests that provider-enforced login timeouts apply before and after pool
initialization.
+ * 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 testProviderEnforcesTimeoutForInitialAndLaterConnections(final
boolean shared) throws Exception {
+ void testUnconfiguredTimeoutPreservesProviderDefault(final boolean shared)
throws Exception {
final RecordingCpds provider = new RecordingCpds();
- provider.enforceTimeout = true;
- try (InstanceKeyDataSource source = newDataSource(shared, false,
provider)) {
- source.setLoginTimeout(Duration.ofMillis(100));
- assertThrows(SQLException.class, source::getConnection);
- assertEquals(9, provider.getLoginTimeout());
- }
- try (InstanceKeyDataSource source = newDataSource(shared, false,
provider)) {
- source.setLoginTimeout(5);
- try (Connection connection = source.getConnection()) {
- assertFalse(connection.isClosed());
- }
- source.setLoginTimeout(Duration.ofMillis(100));
- assertThrows(SQLException.class, source::getConnection);
- assertEquals(9, provider.getLoginTimeout());
- }
- }
-
- /**
- * 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 {
- final SerializableCpds provider = new SerializableCpds();
- try (InstanceKeyDataSource source = newDataSource(shared, false,
provider)) {
- if (configured) {
- source.setLoginTimeout(Duration.ofSeconds(5));
- }
- try (Connection connection = source.getConnection()) {
- assertFalse(connection.isClosed());
- }
- try (InstanceKeyDataSource restored =
deserialize(serialize(source))) {
- assertEquals(source.getLoginTimeoutDuration(),
restored.getLoginTimeoutDuration());
- restored.setLoginTimeout(Duration.ofSeconds(3));
- assertEquals(Duration.ofSeconds(3),
source.getLoginTimeoutDuration());
- provider.attempts.clear();
- try (Connection connection = restored.getConnection()) {
- assertFalse(connection.isClosed());
- }
- assertFalse(provider.attempts.isEmpty());
- provider.attempts.forEach(value -> assertEquals(3,
value.intValue()));
- source.setLoginTimeout(Duration.ofSeconds(7));
- assertEquals(Duration.ofSeconds(7),
restored.getLoginTimeoutDuration());
- provider.attempts.clear();
- try (Connection connection = restored.getConnection()) {
- assertFalse(connection.isClosed());
- }
- assertFalse(provider.attempts.isEmpty());
- provider.attempts.forEach(value -> assertEquals(7,
value.intValue()));
- assertEquals(9, provider.getLoginTimeout());
- }
- }
- }
-
- /**
- * 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());
- }
+ try (InstanceKeyDataSource source = newDataSource(shared, false,
provider);
+ Connection connection = source.getConnection()) {
+ assertFalse(connection.isClosed());
+ assertFalse(provider.attempts.isEmpty());
+ provider.attempts.forEach(value -> assertEquals(9,
value.intValue()));
}
}
@@ -768,71 +884,6 @@ class TestLoginTimeout {
}
}
- /**
- * 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 {
- final SerializableCpds firstProvider = new SerializableCpds();
- final SerializableCpds secondProvider = sameProvider ? firstProvider :
new SerializableCpds();
- // Equal but distinct providers must not share a lock. A changing hash
must not bypass a provider's own lock.
- firstProvider.equalToOtherProviders = !sameProvider;
- secondProvider.equalToOtherProviders = !sameProvider;
- firstProvider.entered = new CountDownLatch(1);
- firstProvider.release = new CountDownLatch(1);
- final ExecutorService executor = Executors.newFixedThreadPool(2);
- try {
- final Future<PooledConnection> first = executor.submit(() ->
ConnectionPoolDataSourceUtils.getPooledConnection(firstProvider,
- null, null, Duration.ofSeconds(1)));
- assertTrue(firstProvider.entered.await(10, TimeUnit.SECONDS));
- final Future<PooledConnection> second = executor.submit(() ->
ConnectionPoolDataSourceUtils.getPooledConnection(secondProvider,
- null, null, Duration.ofSeconds(2)));
- if (sameProvider) {
- assertThrows(TimeoutException.class, () -> second.get(100,
TimeUnit.MILLISECONDS));
- } else {
- assertNotNull(second.get(5, TimeUnit.SECONDS));
- assertEquals(Collections.singletonList(2),
secondProvider.attempts);
- }
- firstProvider.release.countDown();
- first.get(10, TimeUnit.SECONDS).close();
- second.get(10, TimeUnit.SECONDS).close();
- assertEquals(sameProvider ? Arrays.asList(1, 2) :
Collections.singletonList(1), firstProvider.attempts);
- assertEquals(9, firstProvider.getLoginTimeout());
- assertEquals(9, secondProvider.getLoginTimeout());
- } finally {
- firstProvider.release.countDown();
- executor.shutdownNow();
- assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
- }
- }
-
- /**
- * 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 {
- final ConnectionPoolDataSource provider =
mock(ConnectionPoolDataSource.class);
- Thread.currentThread().interrupt();
- try {
- final SQLException failure = assertThrows(SQLException.class, ()
-> ConnectionPoolDataSourceUtils.getPooledConnection(provider,
- null, null, timeout));
- assertInstanceOf(InterruptedException.class, failure.getCause());
- assertTrue(Thread.currentThread().isInterrupted());
- verify(provider, never()).getPooledConnection();
- verify(provider, never()).setLoginTimeout(anyInt());
- } finally {
- Thread.interrupted();
- }
- }
-
/**
* Tests that a positive login timeout bounds the wait for another attempt
to release the provider lock.
*
@@ -861,55 +912,4 @@ 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 {
- final ConnectionPoolDataSource provider =
mock(ConnectionPoolDataSource.class);
- final AtomicInteger timeout = new AtomicInteger(9);
- final AtomicBoolean failOnce = new AtomicBoolean(true);
- final SQLException failure = new SQLException("Provider failure during
" + phase);
- when(provider.getLoginTimeout()).thenAnswer(invocation -> {
- if ("read".equals(phase) && failOnce.getAndSet(false)) {
- throw failure;
- }
- return timeout.get();
- });
- doAnswer(invocation -> {
- final int seconds = invocation.getArgument(0);
- timeout.set(seconds);
- if (("set".equals(phase) && seconds == 1 ||
"restore".equals(phase) && seconds == 9) && failOnce.getAndSet(false)) {
- throw failure;
- }
- return null;
- }).when(provider).setLoginTimeout(anyInt());
- when(provider.getPooledConnection()).thenAnswer(invocation -> {
- if ("connect".equals(phase) && failOnce.getAndSet(false)) {
- throw failure;
- }
- return mock(PooledConnection.class);
- });
- assertSame(failure, assertThrows(SQLException.class, () ->
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
- null, null, Duration.ofSeconds(1))));
- assertEquals(9, timeout.get());
- // A different thread must be able to acquire the provider lock after
every failure path.
- final ExecutorService executor = Executors.newSingleThreadExecutor();
- try {
- final Future<PooledConnection> next = executor.submit(() ->
ConnectionPoolDataSourceUtils.getPooledConnection(provider,
- null, null, Duration.ofSeconds(2)));
- final PooledConnection connection = next.get(5, TimeUnit.SECONDS);
- assertNotNull(connection);
- connection.close();
- assertEquals(9, timeout.get());
- } finally {
- executor.shutdownNow();
- assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
- }
- }
-
}