1 package org.apache.onami.persist;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import javax.inject.Inject;
23 import javax.inject.Singleton;
24 import javax.persistence.EntityTransaction;
25
26 import static org.apache.onami.persist.Preconditions.checkNotNull;
27
28
29
30
31 @Singleton
32 class ResourceLocalTransactionFacadeFactory
33 implements TransactionFacadeFactory
34 {
35
36
37
38
39 private final EntityManagerProvider emProvider;
40
41
42
43
44
45
46 @Inject
47 ResourceLocalTransactionFacadeFactory( EntityManagerProvider emProvider )
48 {
49 this.emProvider = checkNotNull( emProvider, "emProvider is mandatory!" );
50 }
51
52
53
54
55
56 public TransactionFacade createTransactionFacade()
57 {
58 final EntityTransaction txn = emProvider.get().getTransaction();
59 if ( txn.isActive() )
60 {
61 return new Inner( txn );
62 }
63 else
64 {
65 return new Outer( txn );
66 }
67 }
68
69
70
71
72
73
74 private static class Inner
75 implements TransactionFacade
76 {
77 private final EntityTransaction txn;
78
79 Inner( EntityTransaction txn )
80 {
81 this.txn = checkNotNull( txn, "txn is mandatory!" );
82 }
83
84
85
86
87
88 public void begin()
89 {
90
91 }
92
93
94
95
96
97 public void commit()
98 {
99
100 }
101
102
103
104
105
106 public void rollback()
107 {
108 txn.setRollbackOnly();
109 }
110 }
111
112
113
114
115
116
117 private static class Outer
118 implements TransactionFacade
119 {
120 private final EntityTransaction txn;
121
122
123
124
125 Outer( EntityTransaction txn )
126 {
127 this.txn = checkNotNull( txn, "txn is mandatory!" );
128 }
129
130
131
132
133
134 public void begin()
135 {
136 txn.begin();
137 }
138
139
140
141
142
143 public void commit()
144 {
145 if ( txn.getRollbackOnly() )
146 {
147 txn.rollback();
148 }
149 else
150 {
151 txn.commit();
152 }
153 }
154
155
156
157
158
159 public void rollback()
160 {
161 txn.rollback();
162 }
163 }
164
165 }