|
5 | 5 | import java.util.Map; |
6 | 6 | import java.util.concurrent.CountDownLatch; |
7 | 7 | import java.util.concurrent.TimeUnit; |
| 8 | +import javax.annotation.Resource; |
8 | 9 | import javax.interceptor.AroundInvoke; |
9 | 10 | import javax.interceptor.InvocationContext; |
| 11 | +import javax.transaction.Status; |
| 12 | +import javax.transaction.Synchronization; |
| 13 | +import javax.transaction.TransactionSynchronizationRegistry; |
10 | 14 |
|
11 | 15 | /** |
12 | | - * Allows test to wait until a method is invoked. Note that this gets applied as EJB interceptor, and therefore |
13 | | - * returning from {@link #waitFor(java.lang.Class, java.lang.String) } does not guarantee that the bean's transaction |
14 | | - * is already committed. |
| 16 | + * Allows test to wait until a method is invoked. |
15 | 17 | * |
16 | 18 | * @author Patrik Dudits |
17 | 19 | */ |
18 | 20 | public class ReceptionSynchronizer { |
19 | 21 |
|
20 | 22 | private final static Map<Method, CountDownLatch> barrier = new HashMap<>(); |
21 | 23 |
|
| 24 | + @Resource |
| 25 | + TransactionSynchronizationRegistry txRegistry; |
| 26 | + |
22 | 27 | @AroundInvoke |
23 | | - public Object invoke(InvocationContext ctx) throws Exception { |
| 28 | + public Object invoke(final InvocationContext ctx) throws Exception { |
| 29 | + boolean transactional = false; |
24 | 30 | try { |
25 | 31 | System.out.println("Intercepting "+ctx.getMethod().toGenericString()); |
| 32 | + transactional = txRegistry != null && txRegistry.getTransactionStatus() != Status.STATUS_NO_TRANSACTION; |
| 33 | + if (transactional) { |
| 34 | + txRegistry.registerInterposedSynchronization(new Synchronization() { |
| 35 | + @Override |
| 36 | + public void beforeCompletion() { |
| 37 | + |
| 38 | + } |
| 39 | + |
| 40 | + @Override |
| 41 | + public void afterCompletion(int i) { |
| 42 | + registerInvocation(ctx.getMethod()); |
| 43 | + } |
| 44 | + }); |
| 45 | + } |
26 | 46 | return ctx.proceed(); |
27 | 47 | } finally { |
28 | | - registerInvocation(ctx.getMethod()); |
| 48 | + if (!transactional) { |
| 49 | + registerInvocation(ctx.getMethod()); |
| 50 | + } |
29 | 51 | } |
30 | 52 | } |
31 | 53 |
|
@@ -59,7 +81,7 @@ public static void waitFor(Class<?> clazz, String methodName) throws Interrupted |
59 | 81 | } |
60 | 82 |
|
61 | 83 | private static void waitFor(Method method) throws InterruptedException { |
62 | | - CountDownLatch latch = null; |
| 84 | + CountDownLatch latch; |
63 | 85 | synchronized (barrier) { |
64 | 86 | if (barrier.containsKey(method)) { |
65 | 87 | latch = barrier.get(method); |
|
0 commit comments