KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > eb > AccountExplBean


1 /**
2  * JOnAS: Java(TM) Open Application Server
3  * Copyright (C) 1999-2004 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: AccountExplBean.java,v 1.10 2004/04/19 06:39:29 benoitf Exp $
23  * --------------------------------------------------------------------------
24  */

25
26 package eb;
27
28 import java.rmi.RemoteException;
29 import java.sql.Connection;
30 import java.sql.PreparedStatement;
31 import java.sql.ResultSet;
32 import java.sql.SQLException;
33 import java.util.Enumeration;
34 import java.util.Vector;
35
36 import javax.ejb.CreateException;
37 import javax.ejb.EJBException;
38 import javax.ejb.EntityBean;
39 import javax.ejb.EntityContext;
40 import javax.ejb.FinderException;
41 import javax.ejb.ObjectNotFoundException;
42 import javax.ejb.RemoveException;
43 import javax.naming.Context;
44 import javax.naming.InitialContext;
45 import javax.sql.DataSource;
46
47 /**
48  * AccountExplBean is an entity bean with "bean managed persistence". The state
49  * of an instance is stored into a relational database. The following table
50  * should exist: create table ACCOUNT (ACCNO integer primary key, CUSTOMER
51  * varchar(30), BALANCE number(15,4)); Note : In order to keep the code
52  * readable, not all database errors have been handled. In particular the
53  * closing of the statement and of the connexion would have being put in a
54  * "finally" block.
55  * @author JOnAS team
56  */

57
58 public class AccountExplBean implements EntityBean {
59
60     private DataSource dataSource = null;
61
62     // Keep the reference on the EntityContext
63
protected EntityContext entityContext;
64
65     // Object state - must de public (EJB spec.)
66
public Integer accno;
67
68     public String customer;
69
70     public double balance;
71
72     /* ========================= ejbCreate methods ============================ */
73
74     /**
75      * There must be one ejbCreate() method per create() method on the Home
76      * interface, and with the same signature.
77      * @param accno account number
78      * @param customer customer name
79      * @param balance initial balance
80      * @return pk primary key
81      * @exception CreateException If the instance could not perform the function
82      * requested by the container
83      */

84     public Integer ejbCreate(int val_accno, String val_customer, double val_balance) throws CreateException {
85
86         // Init object state
87
accno = new Integer(val_accno);
88         customer = val_customer;
89         balance = val_balance;
90
91         Connection conn = null;
92         PreparedStatement stmt = null;
93         try {
94             // get a connection for this transaction context
95
conn = getConnection();
96
97             // create object in DB
98
stmt = conn.prepareStatement("insert into accountsample_ (accno_, customer_, balance_) values (?, ?, ?)");
99             stmt.setInt(1, accno.intValue());
100             stmt.setString(2, customer);
101             stmt.setDouble(3, balance);
102             stmt.executeUpdate();
103
104         } catch (SQLException e) {
105             throw new CreateException("Failed to create bean in database: " + e);
106         } finally {
107             try {
108                 if (stmt != null) {
109                     //close statement
110
stmt.close();
111                 }
112                 if (conn != null) {
113                     //release connection
114
conn.close();
115                 }
116             } catch (Exception ignore) {
117             }
118         }
119         // Return the primary key
120
return accno;
121     }
122
123     /**
124      * Each ejbCreate method should have a matching ejbPostCreate method
125      */

126     public void ejbPostCreate(int val_accno, String val_customer, double val_balance) {
127         // Nothing to be done for this simple example.
128
}
129
130     /*
131      * ====================== javax.ejb.EntityBean implementation
132      * =================
133      */

134
135     /**
136      * A container invokes this method when the instance is taken out of the
137      * pool of available instances to become associated with a specific EJB
138      * object. This method transitions the instance to the ready state. This
139      * method executes in an unspecified transaction context.
140      * @exception EJBException Thrown by the method to indicate a failure caused
141      * by a system-level error.
142      */

143     public void ejbActivate() {
144         // Nothing to be done for this simple example.
145
}
146
147     /**
148      * A container invokes this method to instruct the instance to synchronize
149      * its state by loading it state from the underlying database. This method
150      * always executes in the proper transaction context.
151      * @exception EJBException Thrown by the method to indicate a failure caused
152      * by a system-level error.
153      * @exception RemoteException - This exception is defined in the method
154      * signature to provide backward compatibility for enterprise
155      * beans written for the EJB 1.0 specification. Enterprise beans
156      * written for the EJB 1.1 and higher specification should throw
157      * the javax.ejb.EJBException instead of this exception.
158      */

159     public void ejbLoad() {
160         Connection conn = null;
161         PreparedStatement stmt = null;
162         try {
163             // get a connection for this transaction context
164
conn = getConnection();
165
166             // find account in DB
167
stmt = conn.prepareStatement("select customer_,balance_ from accountsample_ where accno_=?");
168             Integer pk = (Integer) entityContext.getPrimaryKey();
169             stmt.setInt(1, pk.intValue());
170             ResultSet rs = stmt.executeQuery();
171             if (!rs.next()) {
172                 throw new EJBException("Failed to load bean from database");
173             }
174
175             // update object state
176
accno = pk;
177             customer = rs.getString("customer_");
178             balance = rs.getDouble("balance_");
179
180         } catch (SQLException e) {
181             throw new EJBException("Failed to load bean from database " + e);
182         } finally {
183             try {
184                 if (stmt != null) {
185                     //close statement
186
stmt.close();
187                 }
188                 if (conn != null) {
189                     //release connection
190
conn.close();
191                 }
192             } catch (Exception ignore) {
193             }
194         }
195     }
196
197     /**
198      * A container invokes this method on an instance before the instance
199      * becomes disassociated with a specific EJB object. After this method
200      * completes, the container will place the instance into the pool of
201      * available instances. This method executes in an unspecified transaction
202      * context.
203      * @exception EJBException Thrown by the method to indicate a failure caused
204      * by a system-level error.
205      */

206     public void ejbPassivate() {
207         // Nothing to be done for this simple example.
208
}
209
210     /**
211      * A container invokes this method before it removes the EJB object that is
212      * currently associated with the instance. This method is invoked when a
213      * client invokes a remove operation on the enterprise Bean's home interface
214      * or the EJB object's remote interface. This method transitions the
215      * instance from the ready state to the pool of available instances. This
216      * method is called in the transaction context of the remove operation.
217      * @exception EJBException Thrown by the method to indicate a failure caused
218      * by a system-level error.
219      * @exception RemoteException - This exception is defined in the method
220      * signature to provide backward compatibility for enterprise
221      * beans written for the EJB 1.0 specification. Enterprise beans
222      * written for the EJB 1.1 and higher specification should throw
223      * the javax.ejb.EJBException instead of this exception.
224      * @exception RemoveException The enterprise Bean does not allow destruction
225      * of the object.
226      */

227     public void ejbRemove() throws RemoveException {
228         Connection conn = null;
229         PreparedStatement stmt = null;
230         try {
231             // get a connection for this transaction context
232
conn = getConnection();
233
234             // delete Object in DB
235
stmt = conn.prepareStatement("delete from accountsample_ where accno_=?");
236             Integer pk = (Integer) entityContext.getPrimaryKey();
237             stmt.setInt(1, pk.intValue());
238             stmt.executeUpdate();
239
240         } catch (SQLException e) {
241             throw new RemoveException("Failed to delete bean from database" + e);
242         } finally {
243             try {
244                 if (stmt != null) {
245                     //close statement
246
stmt.close();
247                 }
248                 if (conn != null) {
249                     //release connection
250
conn.close();
251                 }
252             } catch (Exception ignore) {
253             }
254         }
255     }
256
257     /**
258      * A container invokes this method to instruct the instance to synchronize
259      * its state by storing it to the underlying database. This method always
260      * executes in the proper transaction context.
261      * @exception EJBException Thrown by the method to indicate a failure caused
262      * by a system-level error.
263      * @exception RemoteException - This exception is defined in the method
264      * signature to provide backward compatibility for enterprise
265      * beans written for the EJB 1.0 specification. Enterprise beans
266      * written for the EJB 1.1 and higher specification should throw
267      * the javax.ejb.EJBException instead of this exception.
268      */

269     public void ejbStore() {
270         Connection conn = null;
271         PreparedStatement stmt = null;
272         try {
273             // get a connection for this transaction context
274
conn = getConnection();
275
276             // store Object state in DB
277
stmt = conn.prepareStatement("update accountsample_ set customer_=?,balance_=? where accno_=?");
278             stmt.setString(1, customer);
279             stmt.setDouble(2, balance);
280             Integer pk = (Integer) entityContext.getPrimaryKey();
281             stmt.setInt(3, pk.intValue());
282             stmt.executeUpdate();
283
284         } catch (SQLException e) {
285             throw new EJBException("Failed to store bean to database " + e);
286         } finally {
287             try {
288                 if (stmt != null) {
289                     //close statement
290
stmt.close();
291                 }
292                 if (conn != null) {
293                     //release connection
294
conn.close();
295                 }
296             } catch (Exception ignore) {
297             }
298         }
299     }
300
301     /**
302      * Sets the associated entity context. The container invokes this method on
303      * an instance after the instance has been created. This method is called in
304      * an unspecified transaction context.
305      * @param ctx - An EntityContext interface for the instance. The instance
306      * should store the reference to the context in an instance variable.
307      * @exception EJBException Thrown by the method to indicate a failure caused
308      * by a system-level error.
309      * @exception RemoteException - This exception is defined in the method
310      * signature to provide backward compatibility for enterprise
311      * beans written for the EJB 1.0 specification. Enterprise beans
312      * written for the EJB 1.1 and higher specification should throw
313      * the javax.ejb.EJBException instead of this exception.
314      */

315     public void setEntityContext(EntityContext ctx) {
316
317         // Keep the entity context in object
318
entityContext = ctx;
319
320     }
321
322     /**
323      * Unsets the associated entity context. The container calls this method
324      * before removing the instance. This is the last method that the container
325      * invokes on the instance. The Java garbage collector will eventually
326      * invoke the finalize() method on the instance. This method is called in an
327      * unspecified transaction context.
328      * @exception EJBException Thrown by the method to indicate a failure caused
329      * by a system-level error.
330      * @exception RemoteException - This exception is defined in the method
331      * signature to provide backward compatibility for enterprise
332      * beans written for the EJB 1.0 specification. Enterprise beans
333      * written for the EJB 1.1 and higher specification should throw
334      * the javax.ejb.EJBException instead of this exception.
335      */

336     public void unsetEntityContext() {
337         entityContext = null;
338     }
339
340     /* ============================ ejbFind methods =========================== */
341
342     /**
343      * There must be one ejbFind method per find method on the Home interface,
344      * and with the same signature. ejbFindByPrimaryKey is the only mandatory
345      * ejbFind method.
346      * @param pk The primary key
347      * @return pk The primary key
348      * @exception FinderException - Failed to execute the query.
349      * @exception ObjectNotFoundException - Object not found for this primary
350      * key.
351      */

352     public Integer ejbFindByPrimaryKey(Integer pk) throws ObjectNotFoundException, FinderException {
353
354         Connection conn = null;
355         PreparedStatement stmt = null;
356         try {
357             // get a connection for this transaction context
358
conn = getConnection();
359
360             // lookup for this primary key in DB
361
stmt = conn.prepareStatement("select accno_ from accountsample_ where accno_=?");
362             stmt.setInt(1, pk.intValue());
363             ResultSet rs = stmt.executeQuery();
364             if (!rs.next()) {
365                 throw new javax.ejb.ObjectNotFoundException();
366             }
367
368         } catch (SQLException e) {
369             throw new javax.ejb.FinderException("Failed to executeQuery " + e);
370         } finally {
371             try {
372                 if (stmt != null) {
373                     //close statement
374
stmt.close();
375                 }
376                 if (conn != null) {
377                     //release connection
378
conn.close();
379                 }
380             } catch (Exception ignore) {
381             }
382         }
383
384         // return primary key
385
return pk;
386     }
387
388     /**
389      * Find Account by its account number
390      * @return pk The primary key
391      * @exception FinderException - Failed to execute the query.
392      * @exception ObjectNotFoundException - Object not found for this account
393      * number
394      */

395     public Integer ejbFindByNumber(int accno) throws ObjectNotFoundException, FinderException {
396
397         Connection conn = null;
398         PreparedStatement stmt = null;
399         try {
400             // get a connection for this transaction context
401
conn = getConnection();
402             // lookup for this primary key in DB
403
stmt = conn.prepareStatement("select accno_ from accountsample_ where accno_=?");
404             stmt.setInt(1, accno);
405             ResultSet rs = stmt.executeQuery();
406             if (!rs.next()) {
407                 throw new javax.ejb.ObjectNotFoundException();
408             }
409
410         } catch (SQLException e) {
411             throw new javax.ejb.FinderException("Failed to executeQuery " + e);
412         } finally {
413             try {
414                 if (stmt != null) {
415                     //close statement
416
stmt.close();
417                 }
418                 if (conn != null) {
419                     //release connection
420
conn.close();
421                 }
422             } catch (Exception ignore) {
423             }
424         }
425
426         // return a primary key for this account
427
return new Integer(accno);
428     }
429
430     /**
431      * Creates an enumeration of primary keys for all accounts
432      * @return pkv The primary keys
433      * @exception FinderException - Failed to execute the query.
434      */

435     public Enumeration ejbFindAllAccounts() throws FinderException {
436         Connection conn = null;
437         PreparedStatement stmt = null;
438         Vector pkv = new Vector();
439         try {
440             // get a connection for this transaction context
441
conn = getConnection();
442
443             // Lookup for all accounts in DB
444
stmt = conn.prepareStatement("select accno_ from accountsample_");
445             ResultSet rs = stmt.executeQuery();
446
447             // Build the vector of primary keys
448
while (rs.next()) {
449                 Integer pk = new Integer(rs.getInt("accno_"));
450                 pkv.addElement((Object) pk);
451             }
452
453         } catch (SQLException e) {
454             throw new javax.ejb.FinderException("Failed to executeQuery " + e);
455         } finally {
456             try {
457                 if (stmt != null) {
458                     //close statement
459
stmt.close();
460                 }
461                 if (conn != null) {
462                     //release connection
463
conn.close();
464                 }
465             } catch (Exception ignore) {
466             }
467         }
468
469         // return primary keys
470
return pkv.elements();
471     }
472
473     /**
474      * @return the connection from the dataSource
475      * @exception EJBException Thrown by the method if the dataSource is not
476      * found in the naming.
477      * @exception SQLException may be thrown by dataSource.getConnection()
478      */

479     private Connection getConnection() throws EJBException, SQLException {
480         if (dataSource == null) {
481             // Finds DataSource from JNDI
482
Context initialContext = null;
483             try {
484                 initialContext = new InitialContext();
485                 dataSource = (DataSource) initialContext.lookup("java:comp/env/jdbc/AccountExplDs");
486             } catch (Exception e) {
487                 System.out.println("Cannot lookup dataSource" + e);
488                 throw new javax.ejb.EJBException("Cannot lookup dataSource ");
489             }
490         }
491         return dataSource.getConnection();
492     }
493
494     /*
495      * ========================= Account implementation
496      * ============================
497      */

498
499     /**
500      * Business method for returning the balance.
501      * @return balance
502      */

503     public double getBalance() {
504
505         return balance;
506     }
507
508     /**
509      * Business method for updating the balance.
510      * @param d balance to update
511      */

512     public void setBalance(double d) {
513
514         balance = balance + d;
515     }
516
517     /**
518      * Business method for returning the customer.
519      * @return customer
520      */

521     public String getCustomer() {
522
523         return customer;
524     }
525
526     /**
527      * Business method for changing the customer name.
528      * @param c customer to update
529      */

530     public void setCustomer(String c) {
531
532         customer = c;
533     }
534
535     /**
536      * Business method to get the Account number
537      */

538     public int getNumber() {
539         return accno.intValue();
540     }
541 }
Popular Tags