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