1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.kuali.rice.kew.test;
18
19
20 import org.junit.Test;
21 import org.kuali.rice.core.util.DataAccessUtils;
22 import org.springframework.transaction.TransactionStatus;
23 import org.springframework.transaction.support.TransactionCallback;
24 import org.springmodules.orm.ojb.PersistenceBrokerTemplate;
25
26
27
28
29 public abstract class OjbBeanTestCase extends KEWTestCase {
30
31 private Object lock = new Object();
32
33 @Test public void testOptimisticLocking() throws Exception {
34 if (isOptimisticallyLocked()) {
35 getTransactionTemplate().execute(new TransactionCallback() {
36 public Object doInTransaction(TransactionStatus status) {
37 try {
38 Object bean = loadBean();
39 modifyBean(bean);
40 synchronized (lock) {
41 modifyConcurrently();
42 try {
43 lock.wait();
44 } catch (InterruptedException e) {
45 throw new RuntimeException(e);
46 }
47 }
48
49 try {
50 getPersistenceBrokerTemplate().store(bean);
51 fail("The bean was modified by a different transaction, OptimisticLockFailureException should have been thrown.");
52 } catch (Exception e) {
53 if (!DataAccessUtils.isOptimisticLockFailure(e)) {
54 throw e;
55 }
56 }
57 return null;
58 } catch (Exception e) {
59 throw new RuntimeException(e);
60 }
61 }
62 });
63 }
64 }
65
66 private void modifyConcurrently() {
67 Runnable runnable = new Runnable() {
68 public void run() {
69 synchronized (lock) {
70 try {
71 getTransactionTemplate().execute(new TransactionCallback() {
72 public Object doInTransaction(TransactionStatus nestedStatus) {
73 try {
74 Object bean = loadBean();
75 modifyBean(bean);
76 getPersistenceBrokerTemplate().store(bean);
77 return null;
78 } catch (Exception e) {
79 throw new RuntimeException(e);
80 }
81 }
82 });
83 } catch (Throwable t) {
84 t.printStackTrace();
85 fail(t.getMessage());
86 } finally {
87 lock.notify();
88 }
89 }
90 }
91 };
92 new Thread(runnable).start();
93 }
94
95 protected abstract Object loadBean() throws Exception;
96
97 protected abstract void modifyBean(Object bean) throws Exception;
98
99 protected abstract boolean isOptimisticallyLocked();
100
101 protected PersistenceBrokerTemplate getPersistenceBrokerTemplate() {
102 return new PersistenceBrokerTemplate();
103 }
104
105 }