KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > stests > 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.7 2004/12/17 15:09:45 joaninh Exp $
23  * --------------------------------------------------------------------------
24  */

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

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

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

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

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

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

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

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

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

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

178     /**
179      * create a set of Accounts
180      * @param nb nb of Accounts created.
181      */

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

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

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

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

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

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

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

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

346     /**
347      * Create a new Account. The account may exist (for example, when running
348      * tests twice without restarting the Container, or if created by another
349      * session meanwhile)
350      * @param i account number (its PK)
351      */

352     private AccountLocal newAccount(int i) throws RemoteException JavaDoc {
353         AccountLocal ml = null;
354         try {
355             ml = accountLocalHome.create(i, initialValue);
356             history.log(BasicLevel.DEBUG, "New Account\t" + i);
357         } catch (CreateException JavaDoc e) {
358             // Sometimes another one has just created it
359
try {
360                 ml = accountLocalHome.findByNum(i);
361                 history.log(BasicLevel.WARN, "Account was created already : " + i);
362             } catch (FinderException JavaDoc e2) {
363                 history.log(BasicLevel.ERROR, "newAccount:" + e);
364                 throw new RemoteException JavaDoc("Cannot create Account", e);
365             }
366         }
367         return ml;
368     }
369
370     /**
371      * Create an Account if it does not exist yet.
372      * @param c1 num of the Account.
373      */

374     private AccountLocal getAccount(int c1) throws RemoteException JavaDoc {
375         AccountLocal cred1;
376         try {
377             cred1 = accountLocalHome.findByNum(c1);
378         } catch (FinderException JavaDoc e) {
379             cred1 = newAccount(c1);
380         }
381         return cred1;
382     }
383
384     /**
385      * sleep n seconds
386      * @param n seconds
387      */

388     private void sleep(int n) {
389         try {
390             Thread.sleep(1000 * n);
391         } catch (InterruptedException JavaDoc e) {
392         }
393     }
394
395 }
396
Popular Tags