diff --git a/pom.xml b/pom.xml index f994a8377b..357cbe400c 100644 --- a/pom.xml +++ b/pom.xml @@ -226,6 +226,7 @@ ${basedir}/src/conf/checkstyle.xml false + true @@ -346,6 +347,7 @@ ${basedir}/src/conf/checkstyle.xml false + true diff --git a/src/test/java/org/apache/commons/dbcp2/TestAbandonedBasicDataSource.java b/src/test/java/org/apache/commons/dbcp2/TestAbandonedBasicDataSource.java index 0f6232a490..da1d0c2bac 100644 --- a/src/test/java/org/apache/commons/dbcp2/TestAbandonedBasicDataSource.java +++ b/src/test/java/org/apache/commons/dbcp2/TestAbandonedBasicDataSource.java @@ -53,12 +53,10 @@ private void assertAndReset(final DelegatingConnection con) { con.setLastUsed(Instant.EPOCH); } - /** * Verifies that PreparedStatement executeXxx methods update lastUsed on the parent connection */ - private void checkLastUsedPreparedStatement(final PreparedStatement ps, final DelegatingConnection conn) - throws Exception { + private void checkLastUsedPreparedStatement(final PreparedStatement ps, final DelegatingConnection conn) throws Exception { ps.execute(); assertAndReset(conn); try (ResultSet rs = ps.executeQuery()) { @@ -103,7 +101,7 @@ private void checkLastUsedStatement(final Statement st, final DelegatingConnecti assertAndReset(conn); } - private void createStatement(final Connection conn) throws Exception{ + private void createStatement(final Connection conn) throws Exception { final PreparedStatement ps = conn.prepareStatement(""); Assertions.assertNotNull(ps); } @@ -152,8 +150,7 @@ public void testAbandonedClose() throws Exception { // Verify that conn1 is closed assertTrue(((DelegatingConnection) conn1).getInnermostDelegate().isClosed()); // Verify that conn1 is aborted - final TesterConnection tCon = (TesterConnection) ((DelegatingConnection) conn1) - .getInnermostDelegate(); + final TesterConnection tCon = (TesterConnection) ((DelegatingConnection) conn1).getInnermostDelegate(); assertTrue(tCon.isAborted()); } @@ -229,8 +226,7 @@ public void testAbandonedStackTraces() throws Exception { // Verify that conn1 is closed assertTrue(((DelegatingConnection) conn1).getInnermostDelegate().isClosed()); // Verify that conn1 is aborted - final TesterConnection tCon = (TesterConnection) ((DelegatingConnection) conn1) - .getInnermostDelegate(); + final TesterConnection tCon = (TesterConnection) ((DelegatingConnection) conn1).getInnermostDelegate(); assertTrue(tCon.isAborted()); } @@ -244,9 +240,7 @@ public void testAbandonedStackTraces() throws Exception { } /** - * DBCP-180 - verify that a GC can clean up an unused Statement when it is - * no longer referenced even when it is tracked via the AbandonedTrace - * mechanism. + * DBCP-180 - verify that a GC can clean up an unused Statement when it is no longer referenced even when it is tracked via the AbandonedTrace mechanism. */ @Test public void testGarbageCollectorCleanUp01() throws Exception { @@ -269,7 +263,7 @@ public void testGarbageCollectorCleanUp02() throws Exception { final DelegatingConnection conn = (DelegatingConnection) ds.getConnection(); final PoolableConnection poolableConn = (PoolableConnection) conn.getDelegate(); final PoolingConnection poolingConn = (PoolingConnection) poolableConn.getDelegate(); - final KeyedObjectPool gkop = poolingConn.getStatementPool(); + final KeyedObjectPool gkop = poolingConn.getStatementPool(); Assertions.assertEquals(0, conn.getTrace().size()); Assertions.assertEquals(0, gkop.getNumActive()); createStatement(conn); @@ -288,8 +282,7 @@ public void testGarbageCollectorCleanUp02() throws Exception { } /** - * Verify that lastUsed property is updated when a connection - * creates or prepares a statement + * Verify that lastUsed property is updated when a connection creates or prepares a statement */ @Test public void testLastUsed() throws Exception { @@ -321,8 +314,7 @@ public void testLastUsed() throws Exception { } /** - * DBCP-343 - verify that using a DelegatingStatement updates - * the lastUsed on the parent connection + * DBCP-343 - verify that using a DelegatingStatement updates the lastUsed on the parent connection */ @Test public void testLastUsedLargePreparedStatementUse() throws Exception { @@ -353,8 +345,7 @@ public void testLastUsedLargePreparedStatementUse() throws Exception { } /** - * Verify that lastUsed property is updated when a connection - * prepares a callable statement. + * Verify that lastUsed property is updated when a connection prepares a callable statement. */ @Test public void testLastUsedPrepareCall() throws Exception { @@ -386,15 +377,13 @@ public void testLastUsedPrepareCall() throws Exception { } /** - * DBCP-343 - verify that using a DelegatingStatement updates - * the lastUsed on the parent connection + * DBCP-343 - verify that using a DelegatingStatement updates the lastUsed on the parent connection */ @Test public void testLastUsedPreparedStatementUse() throws Exception { ds.setRemoveAbandonedTimeout(Duration.ofSeconds(1)); ds.setMaxTotal(2); - try (Connection conn1 = ds.getConnection(); - Statement st = conn1.createStatement()) { + try (Connection conn1 = ds.getConnection(); Statement st = conn1.createStatement()) { final String querySQL = "SELECT 1 FROM DUAL"; Thread.sleep(500); Assertions.assertNotNull(st.executeQuery(querySQL)); // Should reset lastUsed @@ -405,14 +394,15 @@ public void testLastUsedPreparedStatementUse() throws Exception { Thread.sleep(500); st.executeUpdate(""); // Should also reset Thread.sleep(800); - try (Connection c = ds.getConnection()) {} // trigger abandoned cleanup again - try (Statement s = conn1.createStatement()) {} // Connection should still be good + try (Connection c = ds.getConnection()) { + } // trigger abandoned cleanup again + try (Statement s = conn1.createStatement()) { + } // Connection should still be good } } /** - * DBCP-343 - verify additional operations reset lastUsed on - * the parent connection + * DBCP-343 - verify additional operations reset lastUsed on the parent connection */ @Test public void testLastUsedUpdate() throws Exception { diff --git a/src/test/java/org/apache/commons/dbcp2/TestBasicDataSource.java b/src/test/java/org/apache/commons/dbcp2/TestBasicDataSource.java index 8057d996d0..a294cb0c40 100644 --- a/src/test/java/org/apache/commons/dbcp2/TestBasicDataSource.java +++ b/src/test/java/org/apache/commons/dbcp2/TestBasicDataSource.java @@ -186,8 +186,7 @@ public void testConcurrentInitBorrow() throws Exception { } /** - * JIRA: DBCP-444 - * Verify that invalidate does not return closed connection to the pool. + * JIRA: DBCP-444 Verify that invalidate does not return closed connection to the pool. */ @Test public void testConcurrentInvalidateBorrow() throws Exception { @@ -200,10 +199,10 @@ public void testConcurrentInvalidateBorrow() throws Exception { ds.setMaxWait(Duration.ofMillis(-1)); // Threads just borrow and return - validation will trigger close check - final TestThread testThread1 = new TestThread(1000,0); + final TestThread testThread1 = new TestThread(1000, 0); final Thread t1 = new Thread(testThread1); t1.start(); - final TestThread testThread2 = new TestThread(1000,0); + final TestThread testThread2 = new TestThread(1000, 0); final Thread t2 = new Thread(testThread1); t2.start(); @@ -223,8 +222,7 @@ public void testConcurrentInvalidateBorrow() throws Exception { } /** - * Test disabling MBean registration for Connection objects. - * JIRA: DBCP-585 + * Test disabling MBean registration for Connection objects. JIRA: DBCP-585 */ @Test public void testConnectionMBeansDisabled() throws Exception { @@ -244,8 +242,7 @@ public void testConnectionMBeansDisabled() throws Exception { } /** - * JIRA: DBCP-547 - * Verify that ConnectionFactory interface in BasicDataSource.createConnectionFactory(). + * JIRA: DBCP-547 Verify that ConnectionFactory interface in BasicDataSource.createConnectionFactory(). */ @Test public void testCreateConnectionFactoryWithConnectionFactoryClassName() throws Exception { @@ -266,8 +263,7 @@ public void testCreateConnectionFactoryWithConnectionFactoryClassName() throws E } /** - * JIRA: DBCP-547 - * Verify that ConnectionFactory interface in BasicDataSource.createConnectionFactory(). + * JIRA: DBCP-547 Verify that ConnectionFactory interface in BasicDataSource.createConnectionFactory(). */ @Test public void testCreateConnectionFactoryWithoutConnectionFactoryClassName() throws Exception { @@ -286,9 +282,7 @@ public void testCreateConnectionFactoryWithoutConnectionFactoryClassName() throw } /** - * JIRA: DBCP-342, DBCP-93 - * Verify that when errors occur during BasicDataSource initialization, GenericObjectPool - * Evictors are cleaned up. + * JIRA: DBCP-342, DBCP-93 Verify that when errors occur during BasicDataSource initialization, GenericObjectPool Evictors are cleaned up. */ @Test public void testCreateDataSourceCleanupEvictor() throws Exception { @@ -333,8 +327,7 @@ public void testCreateDataSourceCleanupEvictor() throws Exception { } /** - * JIRA DBCP-93: If an SQLException occurs after the GenericObjectPool is - * initialized in createDataSource, the evictor task is not cleaned up. + * JIRA DBCP-93: If an SQLException occurs after the GenericObjectPool is initialized in createDataSource, the evictor task is not cleaned up. */ @Test public void testCreateDataSourceCleanupThreads() throws Exception { @@ -357,7 +350,7 @@ public void testCreateDataSourceCleanupThreads() throws Exception { ds.setValidationQuery("SELECT DUMMY FROM DUAL"); final int threadCount = Thread.activeCount(); for (int i = 0; i < 10; i++) { - try (Connection c = ds.getConnection()){ + try (Connection c = ds.getConnection()) { } catch (final SQLException ex) { // ignore } @@ -454,9 +447,7 @@ public void testDisconnectionIgnoreSqlCodes() throws Exception { } /** - * JIRA: DBCP-437 - * Verify that BasicDataSource sets disconnect codes properties. - * Functionality is verified in pcf tests. + * JIRA: DBCP-437 Verify that BasicDataSource sets disconnect codes properties. Functionality is verified in pcf tests. */ @Test public void testDisconnectSqlCodes() throws Exception { @@ -475,6 +466,7 @@ public void testDisconnectSqlCodes() throws Exception { /** * JIRA DBCP-333: Check that a custom class loader is used. + * * @throws Exception */ @Test @@ -516,33 +508,32 @@ public void testEmptyValidationQuery() throws Exception { @Test @Disabled - public void testEvict() throws Exception { - final long delay = 1000; - - ds.setInitialSize(10); - ds.setMaxIdle(10); - ds.setMaxTotal(10); - ds.setMinIdle(5); - ds.setNumTestsPerEvictionRun(3); - ds.setMinEvictableIdle(Duration.ofMillis(100)); - ds.setDurationBetweenEvictionRuns(Duration.ofMillis(delay)); - ds.setPoolPreparedStatements(true); - - try (Connection conn = ds.getConnection()) { - // empty - } - - final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); - while (Stream.of(threadBean.getThreadInfo(threadBean.getAllThreadIds())) - .anyMatch(t -> t.getThreadName().equals("commons-pool-evictor-thread"))) { - if (ds.getNumIdle() <= ds.getMinIdle()) { - break; - } - Thread.sleep(delay); - } - assertFalse(ds.getNumIdle() > ds.getMinIdle(), () -> "EvictionTimer thread was destroyed with numIdle=" - + ds.getNumIdle() + "(expected: less or equal than " + ds.getMinIdle() + ")"); - } + public void testEvict() throws Exception { + final long delay = 1000; + + ds.setInitialSize(10); + ds.setMaxIdle(10); + ds.setMaxTotal(10); + ds.setMinIdle(5); + ds.setNumTestsPerEvictionRun(3); + ds.setMinEvictableIdle(Duration.ofMillis(100)); + ds.setDurationBetweenEvictionRuns(Duration.ofMillis(delay)); + ds.setPoolPreparedStatements(true); + + try (Connection conn = ds.getConnection()) { + // empty + } + + final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); + while (Stream.of(threadBean.getThreadInfo(threadBean.getAllThreadIds())).anyMatch(t -> t.getThreadName().equals("commons-pool-evictor-thread"))) { + if (ds.getNumIdle() <= ds.getMinIdle()) { + break; + } + Thread.sleep(delay); + } + assertFalse(ds.getNumIdle() > ds.getMinIdle(), + () -> "EvictionTimer thread was destroyed with numIdle=" + ds.getNumIdle() + "(expected: less or equal than " + ds.getMinIdle() + ")"); + } @Test public void testInitialSize() throws Exception { @@ -559,8 +550,7 @@ public void testInitialSize() throws Exception { } /** - * JIRA: DBCP-482 - * Verify warning not logged if JMX MBean unregistered before close() called. + * JIRA: DBCP-482 Verify warning not logged if JMX MBean unregistered before close() called. */ @Test public void testInstanceNotFoundExceptionLogSuppressed() throws Exception { @@ -615,7 +605,7 @@ public void testInvalidValidationQuery() { assertTrue(e.toString().contains("invalid")); } - // Bugzilla Bug 28251: Returning dead database connections to BasicDataSource + // Bugzilla Bug 28251: Returning dead database connections to BasicDataSource // isClosed() failure blocks returning a connection to the pool @Test public void testIsClosedFailure() throws SQLException { @@ -642,8 +632,7 @@ public void testIsWrapperFor() throws Exception { } /** - * Make sure setting jmxName to null suppresses JMX registration of connection and statement pools. - * JIRA: DBCP-434 + * Make sure setting jmxName to null suppresses JMX registration of connection and statement pools. JIRA: DBCP-434 */ @Test public void testJmxDisabled() throws Exception { @@ -744,9 +733,8 @@ public void testMaxConnLifetimeExceededMutedLog() throws Exception { } /** - * Bugzilla Bug 29832: Broken behavior for BasicDataSource.setMaxTotal(0) - * MaxTotal == 0 should throw SQLException on getConnection. - * Results from Bug 29863 in commons-pool. + * Bugzilla Bug 29832: Broken behavior for BasicDataSource.setMaxTotal(0) MaxTotal == 0 should throw SQLException on getConnection. Results from Bug 29863 + * in commons-pool. */ @Test public void testMaxTotalZero() throws Exception { @@ -755,9 +743,7 @@ public void testMaxTotalZero() throws Exception { } /** - * JIRA: DBCP-457 - * Verify that changes made to abandoned config are passed to the underlying - * pool. + * JIRA: DBCP-457 Verify that changes made to abandoned config are passed to the underlying pool. */ @Test public void testMutateAbandonedConfig() throws Exception { @@ -816,13 +802,12 @@ public void testOverlapBetweenDisconnectionAndIgnoreSqlCodes() { } /** - * Verifies correct handling of exceptions generated by the underlying pool as it closes - * connections in response to BDS#close. Exceptions have to be either swallowed by the - * underlying pool and logged, or propagated and wrapped. + * Verifies correct handling of exceptions generated by the underlying pool as it closes connections in response to BDS#close. Exceptions have to be either + * swallowed by the underlying pool and logged, or propagated and wrapped. */ @Test public void testPoolCloseCheckedException() throws Exception { - ds.setAccessToUnderlyingConnectionAllowed(true); // Allow dirty tricks + ds.setAccessToUnderlyingConnectionAllowed(true); // Allow dirty tricks final TesterConnection tc; // Get an idle connection into the pool @@ -835,7 +820,7 @@ public void testPoolCloseCheckedException() throws Exception { tc.setFailure(new SQLException("bang")); // Now close Datasource, which will cause tc to be closed, triggering SQLE - // Pool 2.x swallows and logs exceptions on pool close. Below verifies that + // Pool 2.x swallows and logs exceptions on pool close. Below verifies that // Either exceptions get logged or wrapped appropriately. try { StackMessageLog.lock(); @@ -885,9 +870,7 @@ public void testPooling() throws Exception { } /** - * Bugzilla Bug 29054: - * The BasicDataSource.setTestOnReturn(boolean) is not carried through to - * the GenericObjectPool variable _testOnReturn. + * Bugzilla Bug 29054: The BasicDataSource.setTestOnReturn(boolean) is not carried through to the GenericObjectPool variable _testOnReturn. */ @Test public void testPropertyTestOnReturn() throws Exception { @@ -932,9 +915,7 @@ public void testRestart() throws Exception { } /** - * Bugzilla Bug 29055: AutoCommit and ReadOnly - * The DaffodilDB driver throws an SQLException if - * trying to commit or rollback a readOnly connection. + * Bugzilla Bug 29055: AutoCommit and ReadOnly The DaffodilDB driver throws an SQLException if trying to commit or rollback a readOnly connection. */ @Test public void testRollbackReadOnly() throws Exception { @@ -1143,8 +1124,7 @@ public void testValidationQueryTimoutFail() { } /** - * TesterDriver that adds latency to connection requests. Latency (in ms) is the - * last component of the URL. + * TesterDriver that adds latency to connection requests. Latency (in ms) is the last component of the URL. */ final class TesterConnectionDelayDriver extends TesterDriver { private static final String CONNECT_STRING = "jdbc:apache:commons:testerConnectionDelayDriver"; diff --git a/src/test/java/org/apache/commons/dbcp2/TestConnectionPool.java b/src/test/java/org/apache/commons/dbcp2/TestConnectionPool.java index cd655d0159..bbd8479a3b 100644 --- a/src/test/java/org/apache/commons/dbcp2/TestConnectionPool.java +++ b/src/test/java/org/apache/commons/dbcp2/TestConnectionPool.java @@ -89,14 +89,14 @@ public PoolTest(final ThreadGroup threadGroup, final Duration connHoldDuration, this(threadGroup, connHoldDuration, isStopOnException, false, 1); } - private PoolTest(final ThreadGroup threadGroup, final Duration connHoldDuration, final boolean isStopOnException, final boolean once, final int numStatements) { + private PoolTest(final ThreadGroup threadGroup, final Duration connHoldDuration, final boolean isStopOnException, final boolean once, + final int numStatements) { this.loopOnce = once; this.connHoldDuration = connHoldDuration; stopOnException = isStopOnException; isRun = true; // Must be done here so main thread is guaranteed to be able to set it false thrown = null; - thread = - new Thread(threadGroup, this, "Thread+" + currentThreadCount++); + thread = new Thread(threadGroup, this, "Thread+" + currentThreadCount++); thread.setDaemon(false); createdMillis = timeStampMillis(); this.numStatements = numStatements; @@ -154,7 +154,7 @@ public void run() { } } - public void start(){ + public void start() { thread.start(); } @@ -219,8 +219,7 @@ public void run() { private static final Duration MAX_WAIT_DURATION = Duration.ofMillis(100); - private static final boolean DISPLAY_THREAD_DETAILS= - Boolean.getBoolean("TestConnectionPool.display.thread.details"); + private static final boolean DISPLAY_THREAD_DETAILS = Boolean.getBoolean("TestConnectionPool.display.thread.details"); // To pass this to a Maven test, use: // mvn test -DargLine="-DTestConnectionPool.display.thread.details=true" // @see https://issues.apache.org/jira/browse/SUREFIRE-121 @@ -232,7 +231,6 @@ public void run() { /** Connections opened during the course of a test */ protected final Stack connectionStack = new Stack<>(); - protected void assertBackPointers(final Connection conn, final Statement statement) throws SQLException { assertFalse(conn.isClosed()); assertFalse(isClosed(statement)); @@ -321,42 +319,37 @@ protected boolean isClosed(final Statement statement) { } /** - * Launches a group of 2 * getMaxTotal() threads, each of which will attempt to obtain a connection - * from the pool, hold it for {@code holdTime} ms, and then return it to the pool. If {@code loopOnce} is false, - * threads will continue this process indefinitely. If {@code expectError} is true, exactly 1/2 of the - * threads are expected to either throw exceptions or fail to complete. If {@code expectError} is false, - * all threads are expected to complete successfully. + * Launches a group of 2 * getMaxTotal() threads, each of which will attempt to obtain a connection from the pool, hold it for {@code holdTime} ms, and then + * return it to the pool. If {@code loopOnce} is false, threads will continue this process indefinitely. If {@code expectError} is true, exactly 1/2 of the + * threads are expected to either throw exceptions or fail to complete. If {@code expectError} is false, all threads are expected to complete successfully. * - * @param holdDuration Duration that a thread holds a connection before returning it to the pool - * @param expectError whether or not an error is expected - * @param loopOnce whether threads should complete the borrow - hold - return cycle only once, or loop indefinitely + * @param holdDuration Duration that a thread holds a connection before returning it to the pool + * @param expectError whether or not an error is expected + * @param loopOnce whether threads should complete the borrow - hold - return cycle only once, or loop indefinitely * @param maxWaitDuration passed in by client - has no impact on the test itself, but does get reported * @throws Exception */ - protected void multipleThreads(final Duration holdDuration, - final boolean expectError, final boolean loopOnce, - final Duration maxWaitDuration) throws Exception { + protected void multipleThreads(final Duration holdDuration, final boolean expectError, final boolean loopOnce, final Duration maxWaitDuration) + throws Exception { multipleThreads(holdDuration, expectError, loopOnce, maxWaitDuration, 1, 2 * getMaxTotal(), 300); } /** - * Launches a group of {@code numThreads} threads, each of which will attempt to obtain a connection - * from the pool, hold it for {@code holdTime} ms, and then return it to the pool. If {@code loopOnce} is false, - * threads will continue this process indefinitely. If {@code expectError} is true, exactly 1/2 of the - * threads are expected to either throw exceptions or fail to complete. If {@code expectError} is false, - * all threads are expected to complete successfully. Threads are stopped after {@code duration} ms. + * Launches a group of {@code numThreads} threads, each of which will attempt to obtain a connection from the pool, hold it for {@code holdTime} ms, and + * then return it to the pool. If {@code loopOnce} is false, threads will continue this process indefinitely. If {@code expectError} is true, exactly 1/2 of + * the threads are expected to either throw exceptions or fail to complete. If {@code expectError} is false, all threads are expected to complete + * successfully. Threads are stopped after {@code duration} ms. * - * @param holdDuration Duration that a thread holds a connection before returning it to the pool - * @param expectError whether or not an error is expected - * @param loopOnce whether threads should complete the borrow - hold - return cycle only once, or loop indefinitely + * @param holdDuration Duration that a thread holds a connection before returning it to the pool + * @param expectError whether or not an error is expected + * @param loopOnce whether threads should complete the borrow - hold - return cycle only once, or loop indefinitely * @param maxWaitDuration passed in by client - has no impact on the test itself, but does get reported - * @param numThreads the number of threads - * @param duration duration in ms of test + * @param numThreads the number of threads + * @param duration duration in ms of test * @throws Exception */ - protected void multipleThreads(final Duration holdDuration, - final boolean expectError, final boolean loopOnce, - final Duration maxWaitDuration, final int numStatements, final int numThreads, final long duration) throws Exception { + protected void multipleThreads(final Duration holdDuration, final boolean expectError, final boolean loopOnce, final Duration maxWaitDuration, + final int numStatements, final int numThreads, final long duration) throws Exception { final long startTimeMillis = timeStampMillis(); final PoolTest[] pts = new PoolTest[numThreads]; // Catch Exception so we can stop all threads if one fails @@ -386,8 +379,8 @@ public void uncaughtException(final Thread t, final Throwable e) { } /* - * Wait for all threads to terminate. This is essential to ensure that all threads have a chance to update success[0] - * and to ensure that the variable is published correctly. + * Wait for all threads to terminate. This is essential to ensure that all threads have a chance to update success[0] and to ensure that the variable is + * published correctly. */ int done = 0; int failed = 0; @@ -414,15 +407,9 @@ public void uncaughtException(final Thread t, final Throwable e) { final long timeMillis = timeStampMillis() - startTimeMillis; // @formatter:off - println("Multithread test time = " + timeMillis - + " ms. Threads: " + pts.length - + ". Loops: " + loops - + ". Hold time: " + holdDuration - + ". maxWaitMillis: " + maxWaitDuration - + ". Done: " + done - + ". Did not run: " + didNotRun - + ". Failed: " + failed - + ". expectError: " + expectError); + println("Multithread test time = " + timeMillis + " ms. Threads: " + pts.length + ". Loops: " + loops + ". Hold time: " + holdDuration + + ". maxWaitMillis: " + maxWaitDuration + ". Done: " + done + ". Did not run: " + didNotRun + ". Failed: " + failed + ". expectError: " + + expectError); // @formatter:on if (expectError) { if (DISPLAY_THREAD_DETAILS || pts.length / 2 != failed) { @@ -431,17 +418,11 @@ public void uncaughtException(final Thread t, final Throwable e) { for (int i = 0; i < pts.length; i++) { final PoolTest pt = pts[i]; // @formatter:off - println("Pre: " + (pt.preconnected-offset) // First, so can sort on this easily - + ". Post: " + (pt.postconnected != 0 ? Long.toString(pt.postconnected-offset): "-") - + ". Hash: " + pt.connHash - + ". Startup: " + (pt.started-pt.createdMillis) - + ". getConn(): " + (pt.connected != 0 ? Long.toString(pt.connected-pt.preconnected) : "-") - + ". Runtime: " + (pt.ended-pt.started) - + ". IDX: " + i - + ". Loops: " + pt.loops - + ". State: " + pt.state - + ". thrown: "+ pt.thrown - + "."); + println("Pre: " + (pt.preconnected - offset) // First, so can sort on this easily + + ". Post: " + (pt.postconnected != 0 ? Long.toString(pt.postconnected - offset) : "-") + ". Hash: " + pt.connHash + ". Startup: " + + (pt.started - pt.createdMillis) + ". getConn(): " + (pt.connected != 0 ? Long.toString(pt.connected - pt.preconnected) : "-") + + ". Runtime: " + (pt.ended - pt.started) + ". IDX: " + i + ". Loops: " + pt.loops + ". State: " + pt.state + ". thrown: " + + pt.thrown + "."); // @formatter:on } } @@ -561,8 +542,7 @@ public void testCanCloseCallableStatementTwice() throws Exception { } /** - * Verify the close method can be called multiple times on a single connection without - * an exception being thrown. + * Verify the close method can be called multiple times on a single connection without an exception being thrown. */ @Test public void testCanCloseConnectionTwice() throws Exception { @@ -695,9 +675,9 @@ public void testClosing() throws Exception { @Test public void testConnectionsAreDistinct() throws Exception { final Connection[] conn = new Connection[getMaxTotal()]; - for(int i=0;i(conn), delegateStmt); assertNotNull(obj.executeQuery()); } @Test public void testExecuteQueryReturnsNull() throws Exception { - final TesterCallableStatement delegateStmt = new TesterCallableStatement(conn,"null"); + final TesterCallableStatement delegateStmt = new TesterCallableStatement(conn, "null"); obj = new DelegatingCallableStatement(new DelegatingConnection<>(conn), delegateStmt); assertNull(obj.executeQuery()); } @@ -251,9 +251,9 @@ public void testGetDateStringCalendar() throws Exception { @Test public void testGetDelegate() throws Exception { - final TesterCallableStatement delegateStmt = new TesterCallableStatement(conn,"select * from foo"); + final TesterCallableStatement delegateStmt = new TesterCallableStatement(conn, "select * from foo"); obj = new DelegatingCallableStatement(new DelegatingConnection<>(conn), delegateStmt); - assertEquals(delegateStmt,((DelegatingCallableStatement)obj).getDelegate()); + assertEquals(delegateStmt, ((DelegatingCallableStatement) obj).getDelegate()); } @Test @@ -1156,4 +1156,4 @@ public void testWasNull() throws Exception { verify(obj, times(1)).wasNull(); } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/commons/dbcp2/TestDelegatingConnection.java b/src/test/java/org/apache/commons/dbcp2/TestDelegatingConnection.java index e4c3b88181..920b8ba39e 100644 --- a/src/test/java/org/apache/commons/dbcp2/TestDelegatingConnection.java +++ b/src/test/java/org/apache/commons/dbcp2/TestDelegatingConnection.java @@ -141,29 +141,29 @@ public void testCheckOpen() throws Exception { * Verify fix for DBCP-241 */ @Test - public void testCheckOpenNull() throws Exception { - delegatingConnection.close(); - SQLException e = assertThrows(SQLException.class, delegatingConnection::checkOpen); - assertTrue(e.getMessage().endsWith("is closed.")); - - delegatingConnection = new DelegatingConnection<>(null); - delegatingConnection.setClosedInternal(true); - e = assertThrows(SQLException.class, delegatingConnection::checkOpen); - assertTrue(e.getMessage().endsWith("is null.")); - - final PoolingConnection pc = new PoolingConnection(connection2); - pc.setStatementPool(new GenericKeyedObjectPool<>(pc)); - delegatingConnection = new DelegatingConnection<>(pc); - pc.close(); - delegatingConnection.close(); - e = assertThrows(SQLException.class, () -> delegatingConnection.prepareStatement("")); - assertTrue(e.getMessage().endsWith("is closed.")); - - delegatingConnection = new DelegatingConnection<>(new RTEGeneratingConnection()); - delegatingConnection.close(); - e = assertThrows(SQLException.class, delegatingConnection::checkOpen); - assertTrue(e.getMessage().endsWith("is closed.")); - } + public void testCheckOpenNull() throws Exception { + delegatingConnection.close(); + SQLException e = assertThrows(SQLException.class, delegatingConnection::checkOpen); + assertTrue(e.getMessage().endsWith("is closed.")); + + delegatingConnection = new DelegatingConnection<>(null); + delegatingConnection.setClosedInternal(true); + e = assertThrows(SQLException.class, delegatingConnection::checkOpen); + assertTrue(e.getMessage().endsWith("is null.")); + + final PoolingConnection pc = new PoolingConnection(connection2); + pc.setStatementPool(new GenericKeyedObjectPool<>(pc)); + delegatingConnection = new DelegatingConnection<>(pc); + pc.close(); + delegatingConnection.close(); + e = assertThrows(SQLException.class, () -> delegatingConnection.prepareStatement("")); + assertTrue(e.getMessage().endsWith("is closed.")); + + delegatingConnection = new DelegatingConnection<>(new RTEGeneratingConnection()); + delegatingConnection.close(); + e = assertThrows(SQLException.class, delegatingConnection::checkOpen); + assertTrue(e.getMessage().endsWith("is closed.")); + } @Test public void testCommit() throws Exception { @@ -365,7 +365,8 @@ public void testSetHoldability() throws Exception { @Test public void testSetNetworkTimeout() throws Exception { - h2DConnection.setNetworkTimeout(r -> {}, 1); + h2DConnection.setNetworkTimeout(r -> { + }, 1); assertEquals(0, h2DConnection.getNetworkTimeout()); } diff --git a/src/test/java/org/apache/commons/dbcp2/TestDelegatingStatement.java b/src/test/java/org/apache/commons/dbcp2/TestDelegatingStatement.java index 7218a0e295..e42d6abc7d 100644 --- a/src/test/java/org/apache/commons/dbcp2/TestDelegatingStatement.java +++ b/src/test/java/org/apache/commons/dbcp2/TestDelegatingStatement.java @@ -60,7 +60,7 @@ public boolean isWrapperFor(final Class iface) throws SQLException { @AfterEach public void afterEach() { - testerResultSet.setSqlExceptionOnClose(false); + testerResultSet.setSqlExceptionOnClose(false); testerStatement.setSqlExceptionOnClose(false); } @@ -97,7 +97,7 @@ public void testCancel() throws Exception { public void testCheckOpen() throws Exception { delegatingStatement.checkOpen(); delegatingStatement.close(); - assertThrows(SQLException.class, delegatingStatement::checkOpen); + assertThrows(SQLException.class, delegatingStatement::checkOpen); } @Test @@ -293,8 +293,7 @@ public void testExecuteUpdateStringStringArray() throws Exception { } /** - * This method is a bit special, and return the delegate connection, not the - * wrapped statement's connection. + * This method is a bit special, and return the delegate connection, not the wrapped statement's connection. * * @throws Exception */ @@ -457,8 +456,7 @@ public void testGetWarnings() throws Exception { } /** - * This method is a bit special, and call isClosed in the delegate object - * itself, not in the wrapped statement. + * This method is a bit special, and call isClosed in the delegate object itself, not in the wrapped statement. * * @throws Exception */ @@ -496,9 +494,7 @@ public void testIsWrapperFor() throws Exception { final DelegatingConnection dconn = new DelegatingConnection<>(tstConn); final DelegatingStatement stamt = new DelegatingStatement(dconn, tstStmt); - final Class stmtProxyClass = Proxy.getProxyClass( - this.getClass().getClassLoader(), - Statement.class); + final Class stmtProxyClass = Proxy.getProxyClass(this.getClass().getClassLoader(), Statement.class); assertTrue(stamt.isWrapperFor(DelegatingStatement.class)); assertTrue(stamt.isWrapperFor(TesterStatement.class)); diff --git a/src/test/java/org/apache/commons/dbcp2/TestDriverManagerConnectionFactory.java b/src/test/java/org/apache/commons/dbcp2/TestDriverManagerConnectionFactory.java index d94065a1d6..c1499b7ab1 100644 --- a/src/test/java/org/apache/commons/dbcp2/TestDriverManagerConnectionFactory.java +++ b/src/test/java/org/apache/commons/dbcp2/TestDriverManagerConnectionFactory.java @@ -31,9 +31,8 @@ import org.junit.jupiter.api.Test; /** - * This test *must* execute before all other tests to be effective as it tests - * the initialization of DriverManager. - * Based on the test case for DBCP-212 written by Marcos Sanz + * This test *must* execute before all other tests to be effective as it tests the initialization of DriverManager. Based on the test case for DBCP-212 written + * by Marcos Sanz */ public class TestDriverManagerConnectionFactory extends AbstractDriverTest { @@ -77,51 +76,49 @@ public String toString() { @Test public void testDriverManagerCredentialsInUrl() throws SQLException { - final DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory("jdbc:apache:commons:testdriver;user=foo;password=bar", null, (char[]) null); + final DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory("jdbc:apache:commons:testdriver;user=foo;password=bar", null, + (char[]) null); cf.createConnection(); } - public void testDriverManagerInit(final boolean withProperties) throws Exception { - final GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); - config.setMaxTotal(10); - config.setMaxIdle(0); - final Properties properties = new Properties(); - // The names "user" and "password" are specified in - // java.sql.DriverManager.getConnection(String, String, String) - properties.setProperty(Constants.KEY_USER, "foo"); - properties.setProperty(Constants.KEY_PASSWORD, "bar"); - final ConnectionFactory connectionFactory = withProperties - ? new DriverManagerConnectionFactory("jdbc:apache:commons:testdriver", properties) - : new DriverManagerConnectionFactory("jdbc:apache:commons:testdriver", "foo", "bar"); - final PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, - null); - poolableConnectionFactory.setDefaultReadOnly(Boolean.FALSE); - poolableConnectionFactory.setDefaultAutoCommit(Boolean.TRUE); - - final GenericObjectPool connectionPool = new GenericObjectPool<>(poolableConnectionFactory, - config); - poolableConnectionFactory.setPool(connectionPool); - final PoolingDataSource dataSource = new PoolingDataSource<>(connectionPool); - - final ConnectionThread[] connectionThreads = new ConnectionThread[10]; - final Thread[] threads = new Thread[10]; - - for (int i = 0; i < 10; i++) { - connectionThreads[i] = new ConnectionThread(dataSource); - threads[i] = new Thread(connectionThreads[i]); - } - for (int i = 0; i < 10; i++) { - threads[i].start(); - } - for (int i = 0; i < 10; i++) { - while (threads[i].isAlive()) { // JDK1.5: getState() != Thread.State.TERMINATED) { - Thread.sleep(100); - } - if (!connectionThreads[i].getResult()) { - fail("Exception during getConnection(): " + connectionThreads[i]); - } - } - } + public void testDriverManagerInit(final boolean withProperties) throws Exception { + final GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); + config.setMaxTotal(10); + config.setMaxIdle(0); + final Properties properties = new Properties(); + // The names "user" and "password" are specified in + // java.sql.DriverManager.getConnection(String, String, String) + properties.setProperty(Constants.KEY_USER, "foo"); + properties.setProperty(Constants.KEY_PASSWORD, "bar"); + final ConnectionFactory connectionFactory = withProperties ? new DriverManagerConnectionFactory("jdbc:apache:commons:testdriver", properties) + : new DriverManagerConnectionFactory("jdbc:apache:commons:testdriver", "foo", "bar"); + final PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null); + poolableConnectionFactory.setDefaultReadOnly(Boolean.FALSE); + poolableConnectionFactory.setDefaultAutoCommit(Boolean.TRUE); + + final GenericObjectPool connectionPool = new GenericObjectPool<>(poolableConnectionFactory, config); + poolableConnectionFactory.setPool(connectionPool); + final PoolingDataSource dataSource = new PoolingDataSource<>(connectionPool); + + final ConnectionThread[] connectionThreads = new ConnectionThread[10]; + final Thread[] threads = new Thread[10]; + + for (int i = 0; i < 10; i++) { + connectionThreads[i] = new ConnectionThread(dataSource); + threads[i] = new Thread(connectionThreads[i]); + } + for (int i = 0; i < 10; i++) { + threads[i].start(); + } + for (int i = 0; i < 10; i++) { + while (threads[i].isAlive()) { // JDK1.5: getState() != Thread.State.TERMINATED) { + Thread.sleep(100); + } + if (!connectionThreads[i].getResult()) { + fail("Exception during getConnection(): " + connectionThreads[i]); + } + } + } @Test public void testDriverManagerInitWithCredentials() throws Exception { @@ -130,8 +127,7 @@ public void testDriverManagerInitWithCredentials() throws Exception { @Test public void testDriverManagerInitWithEmptyProperties() throws Exception { - final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( - "jdbc:apache:commons:testdriver;user=foo;password=bar"); + final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:apache:commons:testdriver;user=foo;password=bar"); connectionFactory.createConnection(); } @@ -142,7 +138,7 @@ public void testDriverManagerInitWithProperties() throws Exception { @Test public void testDriverManagerWithoutCredentials() { - final DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory("jdbc:apache:commons:testdriver", null, (char[]) null); + final DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory("jdbc:apache:commons:testdriver", null, (char[]) null); assertThrows(ArrayIndexOutOfBoundsException.class, cf::createConnection); // thrown by TestDriver due to missing user } diff --git a/src/test/java/org/apache/commons/dbcp2/TestPStmtPooling.java b/src/test/java/org/apache/commons/dbcp2/TestPStmtPooling.java index 674f652071..bc987f7044 100644 --- a/src/test/java/org/apache/commons/dbcp2/TestPStmtPooling.java +++ b/src/test/java/org/apache/commons/dbcp2/TestPStmtPooling.java @@ -45,11 +45,9 @@ public class TestPStmtPooling { private DataSource createPoolingDataSource() throws Exception { DriverManager.registerDriver(new TesterDriver()); - final ConnectionFactory connFactory = new DriverManagerConnectionFactory( - "jdbc:apache:commons:testdriver","u1","p1"); + final ConnectionFactory connFactory = new DriverManagerConnectionFactory("jdbc:apache:commons:testdriver", "u1", "p1"); - final PoolableConnectionFactory pcf = - new PoolableConnectionFactory(connFactory, null); + final PoolableConnectionFactory pcf = new PoolableConnectionFactory(connFactory, null); pcf.setPoolStatements(true); pcf.setDefaultReadOnly(Boolean.FALSE); pcf.setDefaultAutoCommit(Boolean.TRUE); @@ -77,11 +75,9 @@ private PoolablePreparedStatement getPoolablePreparedStatement(Statement s) { @Test public void testBatchUpdate() throws Exception { DriverManager.registerDriver(new TesterDriver()); - final ConnectionFactory connFactory = new DriverManagerConnectionFactory( - "jdbc:apache:commons:testdriver","u1","p1"); + final ConnectionFactory connFactory = new DriverManagerConnectionFactory("jdbc:apache:commons:testdriver", "u1", "p1"); - final PoolableConnectionFactory pcf = - new PoolableConnectionFactory(connFactory, null); + final PoolableConnectionFactory pcf = new PoolableConnectionFactory(connFactory, null); pcf.setPoolStatements(true); pcf.setDefaultReadOnly(Boolean.FALSE); pcf.setDefaultAutoCommit(Boolean.TRUE); @@ -104,12 +100,10 @@ public void testBatchUpdate() throws Exception { @Test public void testCallableStatementPooling() throws Exception { DriverManager.registerDriver(new TesterDriver()); - final ConnectionFactory connFactory = new DriverManagerConnectionFactory( - "jdbc:apache:commons:testdriver","u1","p1"); + final ConnectionFactory connFactory = new DriverManagerConnectionFactory("jdbc:apache:commons:testdriver", "u1", "p1"); final ObjectName oName = new ObjectName("UnitTests:DataSource=test"); - final PoolableConnectionFactory pcf = - new PoolableConnectionFactory(connFactory, oName); + final PoolableConnectionFactory pcf = new PoolableConnectionFactory(connFactory, oName); pcf.setPoolStatements(true); pcf.setDefaultReadOnly(Boolean.FALSE); pcf.setDefaultAutoCommit(Boolean.TRUE); @@ -127,13 +121,13 @@ public void testCallableStatementPooling() throws Exception { final Statement ustmt1 = ((DelegatingStatement) stmt1).getInnermostDelegate(); final Statement cstmt1 = conn.prepareCall("{call home}"); final Statement ucstmt1 = ((DelegatingStatement) cstmt1).getInnermostDelegate(); - stmt1.close(); // Return to pool + stmt1.close(); // Return to pool cstmt1.close(); // "" final Statement stmt2 = conn.prepareStatement("select 1 from dual"); // Check out from pool final Statement ustmt2 = ((DelegatingStatement) stmt2).getInnermostDelegate(); final Statement cstmt2 = conn.prepareCall("{call home}"); final Statement ucstmt2 = ((DelegatingStatement) cstmt2).getInnermostDelegate(); - stmt2.close(); // Return to pool + stmt2.close(); // Return to pool cstmt2.close(); // "" assertSame(ustmt1, ustmt2); assertSame(ucstmt1, ucstmt2); @@ -150,11 +144,9 @@ public void testCallableStatementPooling() throws Exception { @Test public void testClosePool() throws Exception { DriverManager.registerDriver(new TesterDriver()); - final ConnectionFactory connFactory = new DriverManagerConnectionFactory( - "jdbc:apache:commons:testdriver","u1","p1"); + final ConnectionFactory connFactory = new DriverManagerConnectionFactory("jdbc:apache:commons:testdriver", "u1", "p1"); - final PoolableConnectionFactory pcf = - new PoolableConnectionFactory(connFactory, null); + final PoolableConnectionFactory pcf = new PoolableConnectionFactory(connFactory, null); pcf.setPoolStatements(true); pcf.setDefaultReadOnly(Boolean.FALSE); pcf.setDefaultAutoCommit(Boolean.TRUE); @@ -166,11 +158,11 @@ public void testClosePool() throws Exception { ((PoolingDataSource) ds).setAccessToUnderlyingConnectionAllowed(true); final Connection conn = ds.getConnection(); - try (Statement s = conn.prepareStatement("select 1 from dual")) {} + try (Statement s = conn.prepareStatement("select 1 from dual")) { + } final Connection poolableConnection = ((DelegatingConnection) conn).getDelegate(); - final Connection poolingConnection = - ((DelegatingConnection) poolableConnection).getDelegate(); + final Connection poolingConnection = ((DelegatingConnection) poolableConnection).getDelegate(); poolingConnection.close(); final SQLException ex = assertThrows(SQLException.class, () -> conn.prepareStatement("select 1 from dual")); assertTrue(ex.getMessage().endsWith("invalid PoolingConnection.")); @@ -178,30 +170,29 @@ public void testClosePool() throws Exception { } /** - * Verifies that executing close() on an already closed DelegatingStatement - * that wraps a PoolablePreparedStatement does not "re-close" the PPS - * (which could be in use by another client - see DBCP-414). + * Verifies that executing close() on an already closed DelegatingStatement that wraps a PoolablePreparedStatement does not "re-close" the PPS (which could + * be in use by another client - see DBCP-414). */ @Test public void testMultipleClose() throws Exception { - final DataSource ds = createPoolingDataSource(); - final Connection conn = ds.getConnection(); - final PreparedStatement stmt1 = conn.prepareStatement("select 1 from dual"); - final PoolablePreparedStatement pps1 = getPoolablePreparedStatement(stmt1); - conn.close(); - assertTrue(stmt1.isClosed()); // Closing conn should close stmt - stmt1.close(); // Should already be closed - no-op - assertTrue(stmt1.isClosed()); - final Connection conn2 = ds.getConnection(); - final PreparedStatement stmt2 = conn2.prepareStatement("select 1 from dual"); - // Confirm stmt2 now wraps the same PPS wrapped by stmt1 - Assertions.assertSame(pps1, getPoolablePreparedStatement(stmt2)); - stmt1.close(); // close should not cascade to PPS that stmt1 used to wrap + final DataSource ds = createPoolingDataSource(); + final Connection conn = ds.getConnection(); + final PreparedStatement stmt1 = conn.prepareStatement("select 1 from dual"); + final PoolablePreparedStatement pps1 = getPoolablePreparedStatement(stmt1); + conn.close(); + assertTrue(stmt1.isClosed()); // Closing conn should close stmt + stmt1.close(); // Should already be closed - no-op + assertTrue(stmt1.isClosed()); + final Connection conn2 = ds.getConnection(); + final PreparedStatement stmt2 = conn2.prepareStatement("select 1 from dual"); + // Confirm stmt2 now wraps the same PPS wrapped by stmt1 + Assertions.assertSame(pps1, getPoolablePreparedStatement(stmt2)); + stmt1.close(); // close should not cascade to PPS that stmt1 used to wrap assertFalse(stmt2.isClosed()); - stmt2.executeQuery(); // wrapped PPS needs to work here - pre DBCP-414 fix this throws - conn2.close(); - assertTrue(stmt1.isClosed()); - assertTrue(stmt2.isClosed()); + stmt2.executeQuery(); // wrapped PPS needs to work here - pre DBCP-414 fix this throws + conn2.close(); + assertTrue(stmt1.isClosed()); + assertTrue(stmt2.isClosed()); } @Test diff --git a/src/test/java/org/apache/commons/dbcp2/TestParallelCreationWithNoIdle.java b/src/test/java/org/apache/commons/dbcp2/TestParallelCreationWithNoIdle.java index 48ea4aace6..8d70a6b41e 100644 --- a/src/test/java/org/apache/commons/dbcp2/TestParallelCreationWithNoIdle.java +++ b/src/test/java/org/apache/commons/dbcp2/TestParallelCreationWithNoIdle.java @@ -34,7 +34,7 @@ /** * Test if the pooling if no idle objects are used */ -public class TestParallelCreationWithNoIdle { +public class TestParallelCreationWithNoIdle { final class TestThread extends Thread { final Random random = new Random(); @@ -53,8 +53,7 @@ public void run() { // System.out.println("Thread started " + Thread.currentThread().toString()); for (int i = 0; i < iter; i++) { sleepMax(delay); - try (Connection conn = ds.getConnection(); - PreparedStatement stmt = conn.prepareStatement("select 'literal', SYSDATE from dual")) { + try (Connection conn = ds.getConnection(); PreparedStatement stmt = conn.prepareStatement("select 'literal', SYSDATE from dual")) { // System.out.println("Got Connection " + Thread.currentThread().toString()); final ResultSet rset = stmt.executeQuery(); rset.next(); @@ -79,6 +78,7 @@ private void sleepMax(final int timeMax) { } } } + private static final String CATALOG = "test catalog"; protected BasicDataSource ds; @@ -112,8 +112,8 @@ public void setUp() throws Exception { } /** - * Fire up 100 Threads but only have 10 maxActive and forcedBlock. - * See + * Fire up 100 Threads but only have 10 maxActive and forcedBlock. See + * * @throws Exception */ @Test @@ -133,7 +133,7 @@ public void testMassiveConcurrentInitBorrow() throws Exception { for (int i = 0; i < numThreads; i++) { threads[i].start(); - if (i%4 == 0) { + if (i % 4 == 0) { Thread.sleep(20); } } diff --git a/src/test/java/org/apache/commons/dbcp2/TestPoolableConnection.java b/src/test/java/org/apache/commons/dbcp2/TestPoolableConnection.java index 112c0fbdb2..7493c41f18 100644 --- a/src/test/java/org/apache/commons/dbcp2/TestPoolableConnection.java +++ b/src/test/java/org/apache/commons/dbcp2/TestPoolableConnection.java @@ -134,11 +134,10 @@ public void testFastFailValidation() throws Exception { nativeConnection.setFailure(null); // validate should now fail because of previous fatal error, despite cleanup - assertThrows(SQLException.class, () -> conn.validate("SELECT 1", 1000), - "Should throw SQL exception on validation."); + assertThrows(SQLException.class, () -> conn.validate("SELECT 1", 1000), "Should throw SQL exception on validation."); // verify that bad connection does not get returned to the pool - conn.close(); // testOnReturn triggers validate, which should fail + conn.close(); // testOnReturn triggers validate, which should fail assertEquals(0, pool.getNumActive(), "The pool should have no active connections"); assertEquals(0, pool.getNumIdle(), "The pool should have no idle connections"); } @@ -161,7 +160,7 @@ public void testFastFailValidationCustomCodes() throws Exception { nativeConnection.setFailure(null); // verify that bad connection does not get returned to the pool - conn.close(); // testOnReturn triggers validate, which should fail + conn.close(); // testOnReturn triggers validate, which should fail assertEquals(0, pool.getNumActive(), "The pool should have no active connections"); assertEquals(0, pool.getNumIdle(), "The pool should have no idle connections"); } @@ -182,12 +181,11 @@ public void testIsDisconnectionSqlExceptionStackOverflow() throws Exception { } /** - * Tests if the {@link PoolableConnectionMXBean} interface is a valid MXBean - * interface. + * Tests if the {@link PoolableConnectionMXBean} interface is a valid MXBean interface. */ @Test public void testMXBeanCompliance() throws OperationsException { - TestBasicDataSourceMXBean.testMXBeanCompliance(PoolableConnectionMXBean.class); + TestBasicDataSourceMXBean.testMXBeanCompliance(PoolableConnectionMXBean.class); } // Bugzilla Bug 33591: PoolableConnection leaks connections if the @@ -199,7 +197,7 @@ public void testPoolableConnectionLeak() throws Exception { // Now close our innermost delegate, simulating the case where the // underlying connection closes itself - ((PoolableConnection)conn).getInnermostDelegate().close(); + ((PoolableConnection) conn).getInnermostDelegate().close(); // At this point, we can close the pooled connection. The // PoolableConnection *should* realize that its underlying diff --git a/src/test/java/org/apache/commons/dbcp2/TestPoolingDriver.java b/src/test/java/org/apache/commons/dbcp2/TestPoolingDriver.java index 8db94ab06f..d4dced05f7 100644 --- a/src/test/java/org/apache/commons/dbcp2/TestPoolingDriver.java +++ b/src/test/java/org/apache/commons/dbcp2/TestPoolingDriver.java @@ -46,7 +46,7 @@ import org.junit.jupiter.api.Test; /** - * Tests for a {@link GenericObjectPool} based {@link PoolingDriver}. + * Tests for a {@link GenericObjectPool} based {@link PoolingDriver}. */ public class TestPoolingDriver extends TestConnectionPool { @@ -59,7 +59,7 @@ protected Connection getConnection() throws Exception { @BeforeEach public void setUp() throws Exception { - final DriverConnectionFactory cf = new DriverConnectionFactory(new TesterDriver(),"jdbc:apache:commons:testdriver", null); + final DriverConnectionFactory cf = new DriverConnectionFactory(new TesterDriver(), "jdbc:apache:commons:testdriver", null); final PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, null); pcf.setPoolStatements(true); @@ -84,7 +84,7 @@ public void setUp() throws Exception { assertNotNull(pcf); driver = new PoolingDriver(true); - driver.registerPool("test",pool); + driver.registerPool("test", pool); } @Override @@ -96,13 +96,11 @@ public void tearDown() throws Exception { @Test public void test1() { - final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:some:connect:string","userName","password"); - final PoolableConnectionFactory pcf = - new PoolableConnectionFactory(connectionFactory, null); + final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:some:connect:string", "userName", "password"); + final PoolableConnectionFactory pcf = new PoolableConnectionFactory(connectionFactory, null); pcf.setDefaultReadOnly(Boolean.FALSE); pcf.setDefaultAutoCommit(Boolean.TRUE); - final GenericObjectPool connectionPool = - new GenericObjectPool<>(pcf); + final GenericObjectPool connectionPool = new GenericObjectPool<>(pcf); pcf.setPool(connectionPool); final DataSource ds = new PoolingDataSource<>(connectionPool); Assertions.assertNotNull(ds); @@ -110,9 +108,8 @@ public void test1() { @Test public void test2() { - final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:some:connect:string","userName","password"); - final PoolableConnectionFactory pcf = - new PoolableConnectionFactory(connectionFactory, null); + final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:some:connect:string", "userName", "password"); + final PoolableConnectionFactory pcf = new PoolableConnectionFactory(connectionFactory, null); pcf.setDefaultReadOnly(Boolean.FALSE); pcf.setDefaultAutoCommit(Boolean.TRUE); final GenericObjectPool connectionPool = new GenericObjectPool<>(pcf); @@ -169,7 +166,7 @@ public void testLogWriter() throws Exception { ex.printStackTrace(); ex.printStackTrace(ps); ex.printStackTrace(pw); - ex = new SQLException((String)null); + ex = new SQLException((String) null); ex.printStackTrace(); ex.printStackTrace(ps); ex.printStackTrace(pw); @@ -187,7 +184,7 @@ public void testLogWriter() throws Exception { ex.printStackTrace(); ex.printStackTrace(ps); ex.printStackTrace(pw); - ex = new SQLException((String)null); + ex = new SQLException((String) null); ex.printStackTrace(); ex.printStackTrace(ps); ex.printStackTrace(pw); @@ -200,29 +197,24 @@ public void testReportedBug12400() throws Exception { config.setMaxTotal(70); config.setMaxWait(Duration.ofMinutes(1)); config.setMaxIdle(10); - final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( - "jdbc:apache:commons:testdriver", - "userName", - "password"); - final PoolableConnectionFactory poolableConnectionFactory = - new PoolableConnectionFactory(connectionFactory, null); + final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:apache:commons:testdriver", "userName", "password"); + final PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null); poolableConnectionFactory.setDefaultReadOnly(Boolean.FALSE); poolableConnectionFactory.setDefaultAutoCommit(Boolean.TRUE); - final ObjectPool connectionPool = new GenericObjectPool<>(poolableConnectionFactory, - config); + final ObjectPool connectionPool = new GenericObjectPool<>(poolableConnectionFactory, config); poolableConnectionFactory.setPool(connectionPool); assertNotNull(poolableConnectionFactory); final PoolingDriver driver2 = new PoolingDriver(); driver2.registerPool("neusoftim", connectionPool); final Connection[] conn = new Connection[25]; - for(int i=0;i<25;i++) { + for (int i = 0; i < 25; i++) { conn[i] = DriverManager.getConnection("jdbc:apache:commons:dbcp:neusoftim"); - for(int j=0;j T getObject(final String parameterName, final Class type) throws S } @Override - public Object getObject(final String parameterName, final Map> map) throws SQLException { + public Object getObject(final String parameterName, final Map> map) throws SQLException { return null; } @@ -573,8 +573,7 @@ public void setObject(final String parameterName, final Object x, final SQLType } @Override - public void setObject(final String parameterName, final Object x, final SQLType targetSqlType, final int scaleOrLength) - throws SQLException { + public void setObject(final String parameterName, final Object x, final SQLType targetSqlType, final int scaleOrLength) throws SQLException { // Do nothing } diff --git a/src/test/java/org/apache/commons/dbcp2/TesterConnection.java b/src/test/java/org/apache/commons/dbcp2/TesterConnection.java index 449801719c..447cc5712f 100644 --- a/src/test/java/org/apache/commons/dbcp2/TesterConnection.java +++ b/src/test/java/org/apache/commons/dbcp2/TesterConnection.java @@ -47,15 +47,14 @@ public class TesterConnection extends AbandonedTrace implements Connection { protected final DatabaseMetaData metaData = new TesterDatabaseMetaData(); protected String catalog; protected String schema; - protected Map> typeMap; + protected Map> typeMap; protected boolean readOnly; protected SQLWarning warnings; protected final String userName; protected Exception failure; protected boolean sqlExceptionOnClose; - TesterConnection(final String userName, - @SuppressWarnings("unused") final String password) { + TesterConnection(final String userName, @SuppressWarnings("unused") final String password) { this.userName = userName; } @@ -140,10 +139,7 @@ public Statement createStatement(final int resultSetType, final int resultSetCon } @Override - public Statement createStatement(final int resultSetType, - final int resultSetConcurrency, - final int resultSetHoldability) - throws SQLException { + public Statement createStatement(final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) throws SQLException { return createStatement(); } @@ -203,7 +199,7 @@ public int getTransactionIsolation() throws SQLException { } @Override - public Map> getTypeMap() throws SQLException { + public Map> getTypeMap() throws SQLException { checkOpen(); return typeMap; } @@ -271,10 +267,8 @@ public CallableStatement prepareCall(final String sql, final int resultSetType, } @Override - public CallableStatement prepareCall(final String sql, final int resultSetType, - final int resultSetConcurrency, - final int resultSetHoldability) - throws SQLException { + public CallableStatement prepareCall(final String sql, final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) + throws SQLException { checkOpen(); return new TesterCallableStatement(this, sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @@ -296,8 +290,7 @@ public PreparedStatement prepareStatement(final String sql) throws SQLException } @Override - public PreparedStatement prepareStatement(final String sql, final int autoGeneratedKeys) - throws SQLException { + public PreparedStatement prepareStatement(final String sql, final int autoGeneratedKeys) throws SQLException { checkOpen(); return new TesterPreparedStatement(this, sql, autoGeneratedKeys); } @@ -309,23 +302,19 @@ public PreparedStatement prepareStatement(final String sql, final int resultSetT } @Override - public PreparedStatement prepareStatement(final String sql, final int resultSetType, - final int resultSetConcurrency, - final int resultSetHoldability) - throws SQLException { + public PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) + throws SQLException { checkOpen(); return new TesterPreparedStatement(this, sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override - public PreparedStatement prepareStatement(final String sql, final int[] columnIndexes) - throws SQLException { + public PreparedStatement prepareStatement(final String sql, final int[] columnIndexes) throws SQLException { return new TesterPreparedStatement(this, sql, columnIndexes); } @Override - public PreparedStatement prepareStatement(final String sql, final String[] columnNames) - throws SQLException { + public PreparedStatement prepareStatement(final String sql, final String[] columnNames) throws SQLException { return new TesterPreparedStatement(this, sql, columnNames); } @@ -382,8 +371,7 @@ public void setHoldability(final int holdability) throws SQLException { } @Override - public void setNetworkTimeout(final Executor executor, final int milliseconds) - throws SQLException { + public void setNetworkTimeout(final Executor executor, final int milliseconds) throws SQLException { throw new SQLException("Not implemented."); } @@ -406,7 +394,7 @@ public java.sql.Savepoint setSavepoint(final String name) throws SQLException { @Override public void setSchema(final String schema) throws SQLException { checkOpen(); - this.schema= schema; + this.schema = schema; } public void setSqlExceptionOnClose(final boolean sqlExceptionOnClose) { @@ -420,7 +408,7 @@ public void setTransactionIsolation(final int level) throws SQLException { } @Override - public void setTypeMap(final Map> map) throws SQLException { + public void setTypeMap(final Map> map) throws SQLException { checkOpen(); this.typeMap = map; } diff --git a/src/test/java/org/apache/commons/dbcp2/TesterDriver.java b/src/test/java/org/apache/commons/dbcp2/TesterDriver.java index 38e3d5cf63..7ea4bb5093 100644 --- a/src/test/java/org/apache/commons/dbcp2/TesterDriver.java +++ b/src/test/java/org/apache/commons/dbcp2/TesterDriver.java @@ -78,9 +78,8 @@ public boolean acceptsURL(final String url) throws SQLException { return url != null && url.startsWith(CONNECT_STRING); } - private void assertValidUserPassword(final String userName, final String password) - throws SQLException { - if (userName == null){ + private void assertValidUserPassword(final String userName, final String password) throws SQLException { + if (userName == null) { throw new SQLException("user name cannot be null."); } synchronized (validUserPasswords) { @@ -89,8 +88,7 @@ private void assertValidUserPassword(final String userName, final String passwor throw new SQLException(userName + " is not a valid user name."); } if (!realPassword.equals(password)) { - throw new SQLException(password + " is not the correct password for " + userName - + ". The correct password is " + realPassword); + throw new SQLException(password + " is not the correct password for " + userName + ". The correct password is " + realPassword); } } } diff --git a/src/test/java/org/apache/commons/dbcp2/TesterResultSet.java b/src/test/java/org/apache/commons/dbcp2/TesterResultSet.java index f642e333ff..a4d0ccdee8 100644 --- a/src/test/java/org/apache/commons/dbcp2/TesterResultSet.java +++ b/src/test/java/org/apache/commons/dbcp2/TesterResultSet.java @@ -56,15 +56,15 @@ public TesterResultSet(final Statement statement) { } public TesterResultSet(final Statement statement, final int type, final int concurrency) { - this.statement = statement; - this.data = null; - this.type = type; - this.concurrency = concurrency; + this.statement = statement; + this.data = null; + this.type = type; + this.concurrency = concurrency; } public TesterResultSet(final Statement statement, final Object[][] data) { - this.statement = statement; - this.data = data; + this.statement = statement; + this.data = data; } @Override diff --git a/src/test/java/org/apache/commons/dbcp2/TesterUtils.java b/src/test/java/org/apache/commons/dbcp2/TesterUtils.java index 526633c9a1..9f09120d09 100644 --- a/src/test/java/org/apache/commons/dbcp2/TesterUtils.java +++ b/src/test/java/org/apache/commons/dbcp2/TesterUtils.java @@ -18,7 +18,7 @@ import java.lang.reflect.Field; -public class TesterUtils { +public final class TesterUtils { /** * Access a private field. Do it this way rather than increasing the diff --git a/src/test/java/org/apache/commons/dbcp2/cpdsadapter/package-info.java b/src/test/java/org/apache/commons/dbcp2/cpdsadapter/package-info.java new file mode 100644 index 0000000000..e9c776b88a --- /dev/null +++ b/src/test/java/org/apache/commons/dbcp2/cpdsadapter/package-info.java @@ -0,0 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Tests the package {@code org.apache.commons.dbcp2.cpdsadapter}. + */ +package org.apache.commons.dbcp2.cpdsadapter; diff --git a/src/test/java/org/apache/commons/dbcp2/datasources/TestCPDSConnectionFactory.java b/src/test/java/org/apache/commons/dbcp2/datasources/TestCPDSConnectionFactory.java index de052b47ef..503bab49dd 100644 --- a/src/test/java/org/apache/commons/dbcp2/datasources/TestCPDSConnectionFactory.java +++ b/src/test/java/org/apache/commons/dbcp2/datasources/TestCPDSConnectionFactory.java @@ -133,7 +133,7 @@ public void testNullValidationQuery() throws Exception { * JIRA: DBCP-442 */ @Test - public void testNullValidationQuery_Deprecated() throws Exception { + public void testNullValidationQueryDeprecated() throws Exception { final CPDSConnectionFactory factory = new CPDSConnectionFactory(cpds, null, -1, false, "userName", "password"); try (final GenericObjectPool pool = new GenericObjectPool<>(factory)) { factory.setPool(pool); @@ -155,7 +155,7 @@ public void testSetPasswordThenModCharArray() { } @Test - public void testSetPasswordThenModCharArray_Deprecated() { + public void testSetPasswordThenModCharArrayDeprecated() { final CPDSConnectionFactory factory = new CPDSConnectionFactory(cpds, null, -1, false, "userName", "password"); final char[] pwd = {'a'}; factory.setPassword(pwd); diff --git a/src/test/java/org/apache/commons/dbcp2/datasources/TestPerUserPoolDataSource.java b/src/test/java/org/apache/commons/dbcp2/datasources/TestPerUserPoolDataSource.java index 57856a2d09..82eb083c62 100644 --- a/src/test/java/org/apache/commons/dbcp2/datasources/TestPerUserPoolDataSource.java +++ b/src/test/java/org/apache/commons/dbcp2/datasources/TestPerUserPoolDataSource.java @@ -57,7 +57,7 @@ public class TestPerUserPoolDataSource extends TestConnectionPool { @Override protected Connection getConnection() throws SQLException { - return ds.getConnection(user,"bar"); + return ds.getConnection(user, "bar"); } @BeforeEach @@ -121,13 +121,10 @@ public void testChangePassword() throws Exception { @Override @Test - public void testClosing() - throws Exception - { + public void testClosing() throws Exception { final Connection[] c = new Connection[getMaxTotal()]; // open the maximum connections - for (int i=0; i ds.getConnection("u1", "zlsafjk")); + public void testIncorrectPassword() throws SQLException { + // Use bad password + assertThrows(SQLException.class, () -> ds.getConnection("u1", "zlsafjk")); - // Use good password - ds.getConnection("u1", "p1").close(); - final SQLException e = assertThrows(SQLException.class, () -> ds.getConnection("u1", "x"), - "Able to retrieve connection with incorrect password"); - assertTrue(e.getMessage().startsWith("Given password did not match")); + // Use good password + ds.getConnection("u1", "p1").close(); + final SQLException e = assertThrows(SQLException.class, () -> ds.getConnection("u1", "x"), "Able to retrieve connection with incorrect password"); + assertTrue(e.getMessage().startsWith("Given password did not match")); - // Make sure we can still use our good password. - ds.getConnection("u1", "p1").close(); + // Make sure we can still use our good password. + ds.getConnection("u1", "p1").close(); - // Try related users and passwords - ds.getConnection(user, "bar").close(); - assertThrows(SQLException.class, () -> ds.getConnection("foob", "ar")); - assertThrows(SQLException.class, () -> ds.getConnection(user, "baz")); - } + // Try related users and passwords + ds.getConnection(user, "bar").close(); + assertThrows(SQLException.class, () -> ds.getConnection("foob", "ar")); + assertThrows(SQLException.class, () -> ds.getConnection(user, "baz")); + } @Override @Test - public void testMaxTotal() throws Exception { - final Connection[] c = new Connection[getMaxTotal()]; - for (int i = 0; i < c.length; i++) { - c[i] = ds.getConnection(); - assertNotNull(c[i]); - } - // should only be able to open 10 connections, so this test should throw an - // exception - assertThrows(SQLException.class, ds::getConnection, "Allowed to open more than DefaultMaxTotal connections."); - for (final Connection element : c) { - element.close(); - } - } + public void testMaxTotal() throws Exception { + final Connection[] c = new Connection[getMaxTotal()]; + for (int i = 0; i < c.length; i++) { + c[i] = ds.getConnection(); + assertNotNull(c[i]); + } + // should only be able to open 10 connections, so this test should throw an + // exception + assertThrows(SQLException.class, ds::getConnection, "Allowed to open more than DefaultMaxTotal connections."); + for (final Connection element : c) { + element.close(); + } + } /** - * Verify that defaultMaxWaitMillis = 0 means immediate failure when - * pool is exhausted. + * Verify that defaultMaxWaitMillis = 0 means immediate failure when pool is exhausted. */ @Test public void testMaxWaitMillisZero() throws Exception { @@ -339,17 +328,13 @@ public void testMultipleThreads2() throws Exception { @Override @Test - public void testOpening() - throws Exception - { + public void testOpening() throws Exception { final Connection[] c = new Connection[getMaxTotal()]; // test that opening new connections is not closing previous - for (int i=0; i ds.getConnection("u1", "zlsafjk"), - "Able to retrieve connection with incorrect password"); - // Use good password - ds.getConnection("u1", "p1").close(); - final SQLException e = assertThrows(SQLException.class, () -> ds.getConnection("u1", "x"), - "Able to retrieve connection with incorrect password"); - assertTrue(e.getMessage().startsWith("Given password did not match")); - // Make sure we can still use our good password. - ds.getConnection("u1", "p1").close(); - // Try related users and passwords - ds.getConnection("foo", "bar").close(); - assertThrows(SQLException.class, () -> ds.getConnection("u1", "ar")); - assertThrows(SQLException.class, () -> ds.getConnection("u1", "baz")); - } + public void testIncorrectPassword() throws SQLException { + ds.getConnection("u2", "p2").close(); + assertThrows(SQLException.class, () -> ds.getConnection("u1", "zlsafjk"), "Able to retrieve connection with incorrect password"); + // Use good password + ds.getConnection("u1", "p1").close(); + final SQLException e = assertThrows(SQLException.class, () -> ds.getConnection("u1", "x"), "Able to retrieve connection with incorrect password"); + assertTrue(e.getMessage().startsWith("Given password did not match")); + // Make sure we can still use our good password. + ds.getConnection("u1", "p1").close(); + // Try related users and passwords + ds.getConnection("foo", "bar").close(); + assertThrows(SQLException.class, () -> ds.getConnection("u1", "ar")); + assertThrows(SQLException.class, () -> ds.getConnection("u1", "baz")); + } @Override @Test public void testMaxTotal() throws Exception { final Connection[] c = new Connection[getMaxTotal()]; - for (int i=0; i) basicManagedDataSource::getConnection)) { - assertNotNull(connection); - } catch (SQLException e) { - fail(e); - } - } - }); - tm.commit(); - } - } + public void testTransactionSynchronizationRegistry() throws Exception { + try (final BasicManagedDataSource basicManagedDataSource = new BasicManagedDataSource()) { + basicManagedDataSource.setTransactionManager(new TransactionManagerImple()); + final TransactionSynchronizationRegistry tsr = new TransactionSynchronizationRegistryImple(); + basicManagedDataSource.setTransactionSynchronizationRegistry(tsr); + final JdbcDataSource xaDataSource = new JdbcDataSource(); + xaDataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"); + basicManagedDataSource.setXaDataSourceInstance(xaDataSource); + basicManagedDataSource.setMaxIdle(1); + + final TransactionManager tm = basicManagedDataSource.getTransactionManager(); + tm.begin(); + tsr.registerInterposedSynchronization(new SynchronizationAdapter() { + @Override + public void beforeCompletion() { + try (Connection connection = assertDoesNotThrow((ThrowingSupplier) basicManagedDataSource::getConnection)) { + assertNotNull(connection); + } catch (SQLException e) { + fail(e); + } + } + }); + tm.commit(); + } + } @Test public void testXADataSource() throws SQLException { diff --git a/src/test/java/org/apache/commons/dbcp2/managed/TestConnectionWithNarayana.java b/src/test/java/org/apache/commons/dbcp2/managed/TestConnectionWithNarayana.java index c53d32bd5a..4067f47c84 100644 --- a/src/test/java/org/apache/commons/dbcp2/managed/TestConnectionWithNarayana.java +++ b/src/test/java/org/apache/commons/dbcp2/managed/TestConnectionWithNarayana.java @@ -68,8 +68,8 @@ public class TestConnectionWithNarayana { @BeforeEach public void setUp() throws Exception { - jtaPropertyManager.getJTAEnvironmentBean().setLastResourceOptimisationInterfaceClassName( - "org.apache.commons.dbcp2.managed.LocalXAConnectionFactory$LocalXAResource"); + jtaPropertyManager.getJTAEnvironmentBean() + .setLastResourceOptimisationInterfaceClassName("org.apache.commons.dbcp2.managed.LocalXAConnectionFactory$LocalXAResource"); mds = new BasicManagedDataSource(); mds.setTransactionManager(new TransactionManagerImple()); mds.setDriverClassName("org.h2.Driver"); @@ -107,100 +107,97 @@ public void tearDown() throws Exception { } @Test - public void testConnectionCommitAfterTimeout() throws Exception { - mds.getTransactionManager().setTransactionTimeout(1); - mds.getTransactionManager().begin(); - try (Connection conn = mds.getConnection()) { - do { - Thread.sleep(1000); - } while (mds.getTransactionManager().getTransaction().getStatus() != Status.STATUS_ROLLEDBACK); - // Let the reaper do it's thing - Thread.sleep(1000); - final SQLException e = assertThrows(SQLException.class, conn::commit); - assertEquals("Commit cannot be set while enrolled in a transaction", e.getMessage(), - "Should not work after timeout"); - mds.getTransactionManager().rollback(); - } - assertEquals(0, mds.getNumActive()); - } + public void testConnectionCommitAfterTimeout() throws Exception { + mds.getTransactionManager().setTransactionTimeout(1); + mds.getTransactionManager().begin(); + try (Connection conn = mds.getConnection()) { + do { + Thread.sleep(1000); + } while (mds.getTransactionManager().getTransaction().getStatus() != Status.STATUS_ROLLEDBACK); + // Let the reaper do it's thing + Thread.sleep(1000); + final SQLException e = assertThrows(SQLException.class, conn::commit); + assertEquals("Commit cannot be set while enrolled in a transaction", e.getMessage(), "Should not work after timeout"); + mds.getTransactionManager().rollback(); + } + assertEquals(0, mds.getNumActive()); + } @Test - public void testConnectionInTimeout() throws Exception { - Connection conn = null; - PreparedStatement ps = null; - for (int i = 0; i < 5; i++) { - try { - mds.getTransactionManager().setTransactionTimeout(1); - mds.getTransactionManager().begin(); - - conn = mds.getConnection(); - ps = conn.prepareStatement(INSERT_STMT); - ps.setString(1, Thread.currentThread().getName()); - ps.setLong(2, i); - ps.setDouble(3, new java.util.Random().nextDouble()); - ps.setString(4, PAYLOAD); - ps.setTimestamp(5, new Timestamp(System.currentTimeMillis())); - ps.execute(); - - int n = 0; - do { - if (mds.getTransactionManager().getTransaction().getStatus() != Status.STATUS_ACTIVE) { - n++; - } - try (Connection c = mds.getConnection(); - PreparedStatement ps2 = c.prepareStatement(SELECT_STMT); - ResultSet rs = ps2.executeQuery()) { - // nothing here, all auto-close. - } - } while (n < 2); - - ps.close(); - ps = null; - conn.close(); - conn = null; - - assertThrows(RollbackException.class, () -> mds.getTransactionManager().commit()); - // this is expected - if (mds.getTransactionManager().getTransaction() != null) { - // Need to pop it off the thread if a background thread rolled the transaction - // back - mds.getTransactionManager().rollback(); - } - } catch (final Exception e) { - if (mds.getTransactionManager().getTransaction() != null) { - // Need to pop it off the thread if a background thread rolled the transaction - // back - mds.getTransactionManager().rollback(); - } - } finally { - if (ps != null) { - ps.close(); - } - if (conn != null) { - conn.close(); - } - } - Assertions.assertEquals(0, mds.getNumActive()); - } - } + public void testConnectionInTimeout() throws Exception { + Connection conn = null; + PreparedStatement ps = null; + for (int i = 0; i < 5; i++) { + try { + mds.getTransactionManager().setTransactionTimeout(1); + mds.getTransactionManager().begin(); + + conn = mds.getConnection(); + ps = conn.prepareStatement(INSERT_STMT); + ps.setString(1, Thread.currentThread().getName()); + ps.setLong(2, i); + ps.setDouble(3, new java.util.Random().nextDouble()); + ps.setString(4, PAYLOAD); + ps.setTimestamp(5, new Timestamp(System.currentTimeMillis())); + ps.execute(); + + int n = 0; + do { + if (mds.getTransactionManager().getTransaction().getStatus() != Status.STATUS_ACTIVE) { + n++; + } + try (Connection c = mds.getConnection(); PreparedStatement ps2 = c.prepareStatement(SELECT_STMT); ResultSet rs = ps2.executeQuery()) { + // nothing here, all auto-close. + } + } while (n < 2); + + ps.close(); + ps = null; + conn.close(); + conn = null; + + assertThrows(RollbackException.class, () -> mds.getTransactionManager().commit()); + // this is expected + if (mds.getTransactionManager().getTransaction() != null) { + // Need to pop it off the thread if a background thread rolled the transaction + // back + mds.getTransactionManager().rollback(); + } + } catch (final Exception e) { + if (mds.getTransactionManager().getTransaction() != null) { + // Need to pop it off the thread if a background thread rolled the transaction + // back + mds.getTransactionManager().rollback(); + } + } finally { + if (ps != null) { + ps.close(); + } + if (conn != null) { + conn.close(); + } + } + Assertions.assertEquals(0, mds.getNumActive()); + } + } @Test - public void testRepeatedGetConnectionInTimeout() throws Exception { - mds.getTransactionManager().setTransactionTimeout(1); - mds.getTransactionManager().begin(); - try { - do { - Thread.sleep(1000); - } while (mds.getTransactionManager().getTransaction().getStatus() != Status.STATUS_ROLLEDBACK); - // Let the reaper do it's thing - Thread.sleep(1000); - final SQLException e = assertThrows(SQLException.class, mds::getConnection); - assertTrue(e.getCause().getClass().equals(IllegalStateException.class)); - final SQLException e2 = assertThrows(SQLException.class, mds::getConnection); - assertTrue(e2.getCause().getClass().equals(IllegalStateException.class)); - } finally { - mds.getTransactionManager().rollback(); - } - Assertions.assertEquals(0, mds.getNumActive()); - } -} \ No newline at end of file + public void testRepeatedGetConnectionInTimeout() throws Exception { + mds.getTransactionManager().setTransactionTimeout(1); + mds.getTransactionManager().begin(); + try { + do { + Thread.sleep(1000); + } while (mds.getTransactionManager().getTransaction().getStatus() != Status.STATUS_ROLLEDBACK); + // Let the reaper do it's thing + Thread.sleep(1000); + final SQLException e = assertThrows(SQLException.class, mds::getConnection); + assertTrue(e.getCause().getClass().equals(IllegalStateException.class)); + final SQLException e2 = assertThrows(SQLException.class, mds::getConnection); + assertTrue(e2.getCause().getClass().equals(IllegalStateException.class)); + } finally { + mds.getTransactionManager().rollback(); + } + Assertions.assertEquals(0, mds.getNumActive()); + } +} diff --git a/src/test/java/org/apache/commons/dbcp2/managed/TestManagedDataSourceInTx.java b/src/test/java/org/apache/commons/dbcp2/managed/TestManagedDataSourceInTx.java index f83e543642..a353b3a586 100644 --- a/src/test/java/org/apache/commons/dbcp2/managed/TestManagedDataSourceInTx.java +++ b/src/test/java/org/apache/commons/dbcp2/managed/TestManagedDataSourceInTx.java @@ -111,8 +111,7 @@ public void testAutoCommitBehavior() throws Exception { assertFalse(connection.getAutoCommit(), "Auto-commit should be disabled"); // attempt to set auto commit - assertThrows(SQLException.class, () -> connection.setAutoCommit(true), - "setAutoCommit method should be disabled while enlisted in a transaction"); + assertThrows(SQLException.class, () -> connection.setAutoCommit(true), "setAutoCommit method should be disabled while enlisted in a transaction"); // make sure it is still disabled assertFalse(connection.getAutoCommit(), "Auto-commit should be disabled"); @@ -171,23 +170,22 @@ public void testCloseInTransaction() throws Exception { } @Test - public void testCommit() throws Exception { - try (Connection connection = newConnection()) { - // connection should be open - assertFalse(connection.isClosed(), "Connection should be open"); - // attempt commit directly - assertThrows(SQLException.class, connection::commit, - "commit method should be disabled while enlisted in a transaction"); - // make sure it is still open - assertFalse(connection.isClosed(), "Connection should be open"); - - } - } + public void testCommit() throws Exception { + try (Connection connection = newConnection()) { + // connection should be open + assertFalse(connection.isClosed(), "Connection should be open"); + // attempt commit directly + assertThrows(SQLException.class, connection::commit, "commit method should be disabled while enlisted in a transaction"); + // make sure it is still open + assertFalse(connection.isClosed(), "Connection should be open"); + + } + } @Override @Test public void testConnectionReturnOnCommit() throws Exception { - // override with no-op test + // override with no-op test } @Override @@ -231,28 +229,27 @@ public void afterCompletion(final int i) { } @Override - public void beforeCompletion() { - assertDoesNotThrow(() -> conn = (ManagedConnection) ds.getConnection(), "Could not get connection"); - } + public void beforeCompletion() { + assertDoesNotThrow(() -> conn = (ManagedConnection) ds.getConnection(), "Could not get connection"); + } }); transactionManager.commit(); } @Test - public void testGetConnectionInAfterCompletion() throws Exception { - try (DelegatingConnection connection = (DelegatingConnection) newConnection()) { - // Don't close so we can check it for warnings in afterCompletion - transactionManager.getTransaction().registerSynchronization(new SynchronizationAdapter() { - @Override - public void afterCompletion(final int i) { - final Connection connection1 = assertDoesNotThrow((ThrowingSupplier) ds::getConnection); - assertThrows(SQLException.class, () -> connection1.getWarnings(), - "Could operate on closed connection"); - } - }); - } - transactionManager.commit(); - } + public void testGetConnectionInAfterCompletion() throws Exception { + try (DelegatingConnection connection = (DelegatingConnection) newConnection()) { + // Don't close so we can check it for warnings in afterCompletion + transactionManager.getTransaction().registerSynchronization(new SynchronizationAdapter() { + @Override + public void afterCompletion(final int i) { + final Connection connection1 = assertDoesNotThrow((ThrowingSupplier) ds::getConnection); + assertThrows(SQLException.class, () -> connection1.getWarnings(), "Could operate on closed connection"); + } + }); + } + transactionManager.commit(); + } @Override @Test @@ -281,34 +278,33 @@ public void testManagedConnectionEqualsFail() throws Exception { @Override @Test - public void testMaxTotal() throws Exception { - final Transaction[] transactions = new Transaction[getMaxTotal()]; - final Connection[] c = new Connection[getMaxTotal()]; - for (int i = 0; i < c.length; i++) { - // create a new connection in the current transaction - c[i] = newConnection(); - assertNotNull(c[i]); - - // suspend the current transaction and start a new one - transactions[i] = transactionManager.suspend(); - assertNotNull(transactions[i]); - transactionManager.begin(); - } - - try { - assertThrows(SQLException.class, this::newConnection, - "Allowed to open more than DefaultMaxTotal connections."); - // should only be able to open 10 connections, so this test should - // throw an exception - } finally { - transactionManager.commit(); - for (int i = 0; i < c.length; i++) { - transactionManager.resume(transactions[i]); - c[i].close(); - transactionManager.commit(); - } - } - } + public void testMaxTotal() throws Exception { + final Transaction[] transactions = new Transaction[getMaxTotal()]; + final Connection[] c = new Connection[getMaxTotal()]; + for (int i = 0; i < c.length; i++) { + // create a new connection in the current transaction + c[i] = newConnection(); + assertNotNull(c[i]); + + // suspend the current transaction and start a new one + transactions[i] = transactionManager.suspend(); + assertNotNull(transactions[i]); + transactionManager.begin(); + } + + try { + assertThrows(SQLException.class, this::newConnection, "Allowed to open more than DefaultMaxTotal connections."); + // should only be able to open 10 connections, so this test should + // throw an exception + } finally { + transactionManager.commit(); + for (int i = 0; i < c.length; i++) { + transactionManager.resume(transactions[i]); + c[i].close(); + transactionManager.commit(); + } + } + } @Override @Test @@ -323,13 +319,11 @@ public void testReadOnly() throws Exception { // connection should be read only assertTrue(connection.isReadOnly(), "Connection be read-only"); // attempt to setReadOnly - assertThrows(SQLException.class, () -> connection.setReadOnly(true), - "setReadOnly method should be disabled while enlisted in a transaction"); + assertThrows(SQLException.class, () -> connection.setReadOnly(true), "setReadOnly method should be disabled while enlisted in a transaction"); // make sure it is still read-only assertTrue(connection.isReadOnly(), "Connection be read-only"); // attempt to setReadonly - assertThrows(SQLException.class, () -> connection.setReadOnly(false), - "setReadOnly method should be disabled while enlisted in a transaction"); + assertThrows(SQLException.class, () -> connection.setReadOnly(false), "setReadOnly method should be disabled while enlisted in a transaction"); // make sure it is still read-only assertTrue(connection.isReadOnly(), "Connection be read-only"); // TwR closes the connection diff --git a/src/test/java/org/apache/commons/dbcp2/managed/TestPoolableManagedConnection.java b/src/test/java/org/apache/commons/dbcp2/managed/TestPoolableManagedConnection.java index 3f3dd844ee..316201ddb8 100644 --- a/src/test/java/org/apache/commons/dbcp2/managed/TestPoolableManagedConnection.java +++ b/src/test/java/org/apache/commons/dbcp2/managed/TestPoolableManagedConnection.java @@ -140,4 +140,4 @@ public void testReallyClose() throws Exception { assertThrows(SQLException.class, () -> transactionRegistry.getXAResource(conn), "Transaction registry was supposed to be empty now"); assertEquals(0, pool.getNumActive()); } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/commons/dbcp2/managed/package-info.java b/src/test/java/org/apache/commons/dbcp2/managed/package-info.java new file mode 100644 index 0000000000..a221621966 --- /dev/null +++ b/src/test/java/org/apache/commons/dbcp2/managed/package-info.java @@ -0,0 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Tests the package {@code org.apache.commons.dbcp2.managed}. + */ +package org.apache.commons.dbcp2.managed; diff --git a/src/test/java/org/apache/commons/dbcp2/package-info.java b/src/test/java/org/apache/commons/dbcp2/package-info.java new file mode 100644 index 0000000000..07227d97a4 --- /dev/null +++ b/src/test/java/org/apache/commons/dbcp2/package-info.java @@ -0,0 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Tests the package {@code org.apache.commons.dbcp2}. + */ +package org.apache.commons.dbcp2; diff --git a/src/test/java/org/apache/commons/dbcp2/transaction/package-info.java b/src/test/java/org/apache/commons/dbcp2/transaction/package-info.java new file mode 100644 index 0000000000..5126cc774c --- /dev/null +++ b/src/test/java/org/apache/commons/dbcp2/transaction/package-info.java @@ -0,0 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Tests the package {@code org.apache.commons.dbcp2.transaction}. + */ +package org.apache.commons.dbcp2.transaction;