1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.dbcp2.managed;
19
20 import static org.junit.jupiter.api.Assertions.assertEquals;
21
22 import java.lang.reflect.InvocationHandler;
23 import java.lang.reflect.InvocationTargetException;
24 import java.lang.reflect.Method;
25 import java.lang.reflect.Proxy;
26 import java.sql.Connection;
27 import java.sql.SQLException;
28 import java.util.concurrent.atomic.AtomicInteger;
29
30 import javax.sql.XAConnection;
31 import javax.sql.XADataSource;
32
33 import org.apache.commons.dbcp2.TestBasicDataSource;
34 import org.apache.geronimo.transaction.manager.TransactionManagerImpl;
35 import org.junit.jupiter.api.BeforeEach;
36 import org.junit.jupiter.api.Test;
37
38
39
40
41
42 public class TestDataSourceXAConnectionFactory extends TestBasicDataSource {
43
44
45
46
47
48 public final class XADataSourceHandle implements InvocationHandler {
49
50 protected XAConnection getXAConnection() throws SQLException {
51 return new TesterBasicXAConnection(ds.getConnection(), closeCounter);
52 }
53
54 @Override
55 public Object invoke(final Object proxy, final Method method, final Object[] args)
56 throws Throwable {
57 final String methodName = method.getName();
58 switch (methodName) {
59 case "hashCode":
60 return System.identityHashCode(proxy);
61 case "equals":
62 return proxy == args[0];
63 case "getXAConnection":
64
65 return getXAConnection();
66 default:
67 break;
68 }
69 try {
70 return method.invoke(ds, args);
71 } catch (final InvocationTargetException e) {
72 throw e.getTargetException();
73 }
74 }
75 }
76
77 protected BasicManagedDataSource bmds;
78
79 public final AtomicInteger closeCounter = new AtomicInteger();
80
81 @Override
82 @BeforeEach
83 public void setUp() throws Exception {
84 super.setUp();
85 bmds = new BasicManagedDataSource();
86 bmds.setTransactionManager(new TransactionManagerImpl());
87 bmds.setXADataSource("notnull");
88 final XADataSourceHandle handle = new XADataSourceHandle();
89 final XADataSource xads = (XADataSource) Proxy.newProxyInstance(
90 XADataSourceHandle.class.getClassLoader(),
91 new Class[] { XADataSource.class }, handle);
92 bmds.setXaDataSourceInstance(xads);
93 }
94
95
96
97
98 @Test
99 void testPhysicalClose() throws Exception {
100 bmds.setMaxIdle(1);
101 final Connection conn1 = bmds.getConnection();
102 final Connection conn2 = bmds.getConnection();
103 closeCounter.set(0);
104 conn1.close();
105 assertEquals(0, closeCounter.get());
106 conn2.close();
107 assertEquals(1, closeCounter.get());
108 bmds.close();
109 assertEquals(2, closeCounter.get());
110 }
111
112 }
113