1 package org.apache.ojb.odmg;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 import org.apache.ojb.broker.OJBRuntimeException;
19 import org.apache.ojb.broker.PBFactoryException;
20 import org.apache.ojb.broker.PBKey;
21 import org.apache.ojb.broker.PersistenceBroker;
22 import org.apache.ojb.broker.PersistenceBrokerFactory;
23 import org.apache.ojb.broker.util.logging.Logger;
24 import org.apache.ojb.broker.util.logging.LoggerFactory;
25 import org.odmg.Transaction;
26
27 public final class PBCapsule
28 {
29 private static Logger log = LoggerFactory.getLogger(PBCapsule.class);
30
31 PersistenceBroker broker;
32 PBKey pbKey;
33 Transaction tx;
34 boolean needsTxCommit = false;
35 boolean needsPBCommit = false;
36 boolean isIlleagal = false;
37
38 public PBCapsule(final PBKey pbKey, final Transaction tx)
39 {
40 this.tx = tx;
41 this.pbKey = pbKey;
42 prepare();
43 }
44
45 public PersistenceBroker getBroker()
46 {
47 if(isIlleagal) throw new OJBRuntimeException("You could not reuse PBCapsule after destroy");
48 return broker;
49 }
50
51 private void prepare()
52 {
53 if(isIlleagal) throw new OJBRuntimeException("You could not reuse PBCapsule after destroy");
54
55
56
57 if (tx == null)
58 {
59 if (log.isDebugEnabled())
60 log.debug("No running transaction found, try to get " +
61 "PersistenceBroker instance via PBKey " + pbKey);
62 broker = obtainBroker();
63
64 if (!broker.isInTransaction())
65 {
66 broker.beginTransaction();
67 needsPBCommit = true;
68 }
69 }
70 else
71 {
72
73
74 if (!tx.isOpen())
75 {
76 tx.begin();
77 needsTxCommit = true;
78 }
79
80 broker = ((HasBroker) tx).getBroker();
81 }
82 }
83
84 public void destroy()
85 {
86 if (needsTxCommit)
87 {
88 if (log.isDebugEnabled()) log.debug("Indicated to commit tx");
89 tx.commit();
90 }
91 else if (needsPBCommit)
92 {
93 if (log.isDebugEnabled()) log.debug("Indicated to commit PersistenceBroker");
94 try
95 {
96 broker.commitTransaction();
97 }
98 finally
99 {
100 if (broker != null) broker.close();
101 }
102 }
103 isIlleagal = true;
104 needsTxCommit = false;
105 needsPBCommit = false;
106 }
107
108
109
110
111 private PersistenceBroker obtainBroker()
112 {
113 PersistenceBroker _broker;
114 try
115 {
116 if (pbKey == null)
117 {
118
119 log.warn("No tx runnning and PBKey is null, try to use the default PB");
120 _broker = PersistenceBrokerFactory.defaultPersistenceBroker();
121 }
122 else
123 {
124 _broker = PersistenceBrokerFactory.createPersistenceBroker(pbKey);
125 }
126 }
127 catch (PBFactoryException e)
128 {
129 log.error("Could not obtain PB for PBKey " + pbKey, e);
130 throw new OJBRuntimeException("Unexpected micro-kernel exception", e);
131 }
132 return _broker;
133 }
134 }