KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > jtests > beans > bank > ManagerSF


1 /*
2  * JOnAS: Java(TM) Open Application Server
3  * Copyright (C) 1999 Bull S.A.
4  * Contact: jonas-team@objectweb.org
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19  * USA
20  *
21  * --------------------------------------------------------------------------
22  * $Id: ManagerSF.java,v 1.3 2004/12/17 15:08:36 joaninh Exp $
23  * --------------------------------------------------------------------------
24  */

25
26 package org.objectweb.jonas.jtests.beans.bank;
27
28 import java.rmi.NoSuchObjectException JavaDoc;
29 import java.rmi.RemoteException JavaDoc;
30 import java.util.Collection JavaDoc;
31 import java.util.Iterator JavaDoc;
32
33 import javax.ejb.CreateException JavaDoc;
34 import javax.ejb.EJBException JavaDoc;
35 import javax.ejb.FinderException JavaDoc;
36 import javax.ejb.NoSuchObjectLocalException JavaDoc;
37 import javax.ejb.RemoveException JavaDoc;
38 import javax.ejb.SessionBean JavaDoc;
39 import javax.ejb.SessionContext JavaDoc;
40 import javax.ejb.SessionSynchronization JavaDoc;
41 import javax.ejb.TransactionRolledbackLocalException JavaDoc;
42 import javax.naming.Context JavaDoc;
43 import javax.naming.InitialContext JavaDoc;
44 import javax.naming.NamingException JavaDoc;
45 import javax.rmi.PortableRemoteObject JavaDoc;
46
47 import org.objectweb.jonas.common.Log;
48 import org.objectweb.util.monolog.api.BasicLevel;
49 import org.objectweb.util.monolog.api.Logger;
50
51 /**
52  * Manager Implementation
53  * @author Philippe Durieux
54  */

55 public class ManagerSF implements SessionBean JavaDoc, SessionSynchronization JavaDoc {
56
57     protected static Logger history = null;
58     SessionContext JavaDoc ejbContext;
59     AccountLocalHome accountLocalHome = null;
60     AccountLocal last = null;
61     int initialValue;
62
63     // ------------------------------------------------------------------
64
// SessionBean implementation
65
// ------------------------------------------------------------------
66

67     /**
68      * Set the associated session context. The container calls this method
69      * after the instance creation.
70      * The enterprise Bean instance should store the reference to the context
71      * object in an instance variable.
72      * This method is called with no transaction context.
73      *
74      * @param ctx A SessionContext interface for the instance.
75      * @throws EJBException Thrown by the method to indicate a failure caused by
76      * a system-level error.
77      */

78     public void setSessionContext(SessionContext JavaDoc ctx) {
79         if (history == null) {
80             history = Log.getLogger("org.objectweb.jonas_tests.history");
81         }
82         history.log(BasicLevel.DEBUG, "");
83         ejbContext = ctx;
84     }
85
86     /**
87      * A container invokes this method before it ends the life of the session object.
88      * This happens as a result of a client's invoking a remove operation, or when a
89      * container decides to terminate the session object after a timeout.
90      * This method is called with no transaction context.
91      *
92      * @throws EJBException Thrown by the method to indicate a failure caused by
93      * a system-level error.
94      */

95     public void ejbRemove() {
96         history.log(BasicLevel.DEBUG, "");
97     }
98
99     /**
100      * Create a session.
101      * @param ival initial balance value for new accounts.
102      * @throws CreateException Failure to create a session EJB object.
103      */

104     public void ejbCreate(int ival) throws CreateException JavaDoc {
105         history.log(BasicLevel.DEBUG, "");
106
107         // lookup AccountLocalHome
108
try {
109             Context JavaDoc ictx = new InitialContext JavaDoc();
110             accountLocalHome = (AccountLocalHome) ictx.lookup("java:comp/env/ejb/bank");
111         } catch (NamingException JavaDoc e) {
112             history.log(BasicLevel.ERROR, "Cannot get AccountLocalHome:" + e);
113             throw new CreateException JavaDoc("Cannot get AccountLocalHome");
114         }
115
116         initialValue = ival;
117     }
118
119     /**
120      * Create a session.
121      * @param ival initial balance value for new accounts.
122      * @throws CreateException Failure to create a session EJB object.
123      */

124     public void ejbCreate(int ival, boolean prefetch) throws CreateException JavaDoc {
125         history.log(BasicLevel.DEBUG, "");
126
127         // lookup AccountLocalHome
128
try {
129             Context JavaDoc ictx = new InitialContext JavaDoc();
130             String JavaDoc ejblink = prefetch ? "java:comp/env/ejb/bankpf" : "java:comp/env/ejb/bank";
131             accountLocalHome = (AccountLocalHome) ictx.lookup(ejblink);
132         } catch (NamingException JavaDoc e) {
133             history.log(BasicLevel.ERROR, "Cannot get AccountLocalHome:" + e);
134             throw new CreateException JavaDoc("Cannot get AccountLocalHome");
135         }
136
137         initialValue = ival;
138     }
139
140     /**
141      * A container invokes this method on an instance before the instance
142      * becomes disassociated with a specific EJB object.
143      */

144     public void ejbPassivate() {
145         history.log(BasicLevel.DEBUG, "");
146     }
147
148     /**
149      * A container invokes this method when the instance is taken out of
150      * the pool of available instances to become associated with a specific
151      * EJB object.
152      */

153     public void ejbActivate() {
154         history.log(BasicLevel.DEBUG, "");
155     }
156     
157     // ------------------------------------------------------------------
158
// SessionSynchronization implementation
159
// ------------------------------------------------------------------
160

161     public void afterBegin() {
162         history.log(BasicLevel.DEBUG, "");
163     }
164
165     public void beforeCompletion() {
166         history.log(BasicLevel.DEBUG, "");
167     }
168
169     public void afterCompletion(boolean committed) {
170         if (committed) {
171             history.log(BasicLevel.DEBUG, "TX committed");
172         } else {
173             history.log(BasicLevel.DEBUG, "TX rolled back");
174         }
175     }
176
177     // ------------------------------------------------------------------
178
// Manager implementation
179
// ------------------------------------------------------------------
180

181     /**
182      * create a set of Accounts
183      * @param nb nb of Accounts created.
184      */

185     public void createAll(int nb) throws RemoteException JavaDoc {
186         // Check if accounts are already created.
187
try {
188             accountLocalHome.findByNum(nb - 1);
189         } catch (Exception JavaDoc e) {
190             // create accounts
191
for (int i = 0; i < nb; i++) {
192                 newAccount(i);
193             }
194         }
195     }
196
197     /**
198      * reinit all created accounts to their initial value.
199      */

200     public void reinitAll() throws RemoteException JavaDoc {
201         try {
202             Collection JavaDoc coll = accountLocalHome.findAll();
203             for (Iterator JavaDoc it = coll.iterator(); it.hasNext();) {
204                 AccountLocal a = (AccountLocal) it.next();
205                 a.setBalance(initialValue);
206             }
207         } catch (Exception JavaDoc e) {
208             history.log(BasicLevel.ERROR, "reinitAll:" + e);
209         }
210     }
211
212
213     /**
214      * Remove an Account
215      * @param d1 num of the Account.
216      */

217     public void delAccount(int d1) throws RemoteException JavaDoc, RemoveException JavaDoc {
218         try {
219             AccountLocal deb1 = accountLocalHome.findByNum(d1);
220             deb1.remove();
221             history.log(BasicLevel.DEBUG, d1 + "\tREMOVED");
222         } catch (FinderException JavaDoc e) {
223             history.log(BasicLevel.INFO, d1 + "\tNot Found for remove");
224         }
225     }
226
227     /**
228      * Check all existing Accounts
229      * @return true if all are OK.
230      */

231     public boolean checkAll() throws RemoteException JavaDoc {
232         int count = 0;
233         int total = 0;
234         try {
235             Collection JavaDoc coll = accountLocalHome.findAll();
236             for (Iterator JavaDoc it = coll.iterator(); it.hasNext();) {
237                 count++;
238                 AccountLocal a = (AccountLocal) it.next();
239                 int balance = a.getBalance();
240                 if (balance < 0) {
241                     history.log(BasicLevel.ERROR, "checkAllAccounts: bad balance: " + balance);
242                     return false;
243                 }
244                 String JavaDoc name = a.getName();
245                 history.log(BasicLevel.DEBUG, name + " : FINAL BALANCE=" + balance);
246                 total += balance;
247             }
248         } catch (Exception JavaDoc e) {
249             history.log(BasicLevel.ERROR, "checkAllAccounts:" + e);
250             return false;
251         }
252         int exp = initialValue * count;
253         if (total != exp) {
254             history.log(BasicLevel.ERROR, "checkAllAccounts: bad total: " + total + " (expected: " + exp + ")");
255             return false;
256         }
257         history.log(BasicLevel.DEBUG, "CheckAll OK");
258         return true;
259     }
260
261     /**
262      * Check an existing Account
263      * @param a num of the Account.
264      * @return true if OK.
265      */

266     public boolean checkAccount(int a) throws RemoteException JavaDoc {
267         boolean ret = false;
268         AccountLocal m = null;
269
270         // retry several times, because this operation may be rolledback
271
// in case of deadlock.
272
Exception JavaDoc exc = null;
273         int retry;
274         for (retry = 0; retry < 20; retry++) {
275             try {
276                 history.log(BasicLevel.DEBUG, "\ta_" + a + "\tCHECKED try #" + retry);
277                 m = accountLocalHome.findByNum(a);
278                 int b = m.getBalance();
279                 if (b >= 0) {
280                     ret = true;
281                 } else {
282                     history.log(BasicLevel.WARN, "bad balance=" + b);
283                 }
284                 return ret;
285             } catch (Exception JavaDoc e) {
286                 exc = e;
287                 history.log(BasicLevel.DEBUG, "retrying " + retry);
288                 sleep(retry + 1);
289             }
290         }
291         history.log(BasicLevel.WARN, "cannot check account: " + exc);
292         return ret;
293     }
294
295     /*
296      * read balance for this Account, in a transaction.
297      * @param a num of the Account.
298      * @return balance
299      */

300     public int readBalanceTx(int a) throws RemoteException JavaDoc {
301         return readBalance(a);
302     }
303
304     /**
305      * read balance for this Account
306      * @param a num of the Account.
307      * @return balance
308      */

309     public int readBalance(int a) throws RemoteException JavaDoc {
310         int ret;
311         try {
312             ret = getAccount(a).getBalance();
313         } catch (Exception JavaDoc e) {
314             history.log(BasicLevel.ERROR, "Cannot read balance for " + a + ": " + e);
315             throw new RemoteException JavaDoc("Cannot read balance for " + a);
316         }
317         history.log(BasicLevel.DEBUG, "READ " + a + " = " + ret);
318         return ret;
319     }
320
321     /**
322      * move form an Account to another one.
323      * @param d num of the debit Account.
324      * @param c num of the credit Account.
325      * @param v value to be moved
326      * @param d delay in second for the operation.
327      */

328     public void move(int d, int c, int v, int delay) throws RemoteException JavaDoc {
329         history.log(BasicLevel.DEBUG, "MOVE " + v + " from " + d + " to " + c);
330         try {
331             AccountLocal cred = getAccount(c);
332             AccountLocal deb = getAccount(d);
333             cred.credit(v);
334             sleep(delay);
335             deb.debit(v);
336         } catch (TransactionRolledbackLocalException JavaDoc e) {
337             history.log(BasicLevel.WARN, "move: Rollback transaction");
338             return;
339         } catch (EJBException JavaDoc e) {
340             history.log(BasicLevel.ERROR, "Cannot move:" + e);
341             return;
342         }
343     }
344
345     /**
346      * Read balance on last accessed account
347      */

348     public int readBalance() throws RemoteException JavaDoc {
349         int ret;
350         try {
351             ret = last.getBalance();
352         } catch (NoSuchObjectLocalException JavaDoc e) {
353             throw new NoSuchObjectException JavaDoc("Account destroyed");
354         } catch (Exception JavaDoc e) {
355             throw new RemoteException JavaDoc("Cannot read last balance");
356         }
357         return ret;
358     }
359
360     // ------------------------------------------------------------------
361
// private methods
362
// ------------------------------------------------------------------
363

364     /**
365      * Create a new Account. The account may exist (for example, when running
366      * tests twice without restarting the Container, or if created by another
367      * session meanwhile)
368      * @param i account number (its PK)
369      */

370     private AccountLocal newAccount(int i) throws RemoteException JavaDoc {
371         AccountLocal ml = null;
372         try {
373             ml = accountLocalHome.create(i, initialValue);
374             history.log(BasicLevel.DEBUG, "New Account\t" + i);
375         } catch (CreateException JavaDoc e) {
376             // Sometimes another one has just created it
377
try {
378                 ml = accountLocalHome.findByNum(i);
379                 history.log(BasicLevel.WARN, "Account was created already : " + i);
380             } catch (FinderException JavaDoc e2) {
381                 history.log(BasicLevel.ERROR, "newAccount:" + e);
382                 throw new RemoteException JavaDoc("Cannot create Account", e);
383             }
384         }
385         return ml;
386     }
387
388     /**
389      * Create an Account if it does not exist yet.
390      * @param c1 num of the Account.
391      */

392     private AccountLocal getAccount(int c1) throws RemoteException JavaDoc {
393         try {
394             last = accountLocalHome.findByNum(c1);
395         } catch (FinderException JavaDoc e) {
396             last = newAccount(c1);
397         }
398         return last;
399     }
400
401     /**
402      * sleep n seconds
403      * @param n seconds
404      */

405     private void sleep(int n) {
406         try {
407             Thread.sleep(1000 * n);
408         } catch (InterruptedException JavaDoc e) {
409         }
410     }
411
412 }
413
Popular Tags