KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > bank > SavingsAccountBean


1 /*
2  * Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved. U.S.
3  * Government Rights - Commercial software. Government users are subject
4  * to the Sun Microsystems, Inc. standard license agreement and
5  * applicable provisions of the FAR and its supplements. Use is subject
6  * to license terms.
7  *
8  * This distribution may include materials developed by third parties.
9  * Sun, Sun Microsystems, the Sun logo, Java and J2EE are trademarks
10  * or registered trademarks of Sun Microsystems, Inc. in the U.S. and
11  * other countries.
12  *
13  * Copyright (c) 2005 Sun Microsystems, Inc. Tous droits reserves.
14  *
15  * Droits du gouvernement americain, utilisateurs gouvernementaux - logiciel
16  * commercial. Les utilisateurs gouvernementaux sont soumis au contrat de
17  * licence standard de Sun Microsystems, Inc., ainsi qu'aux dispositions
18  * en vigueur de la FAR (Federal Acquisition Regulations) et des
19  * supplements a celles-ci. Distribue par des licences qui en
20  * restreignent l'utilisation.
21  *
22  * Cette distribution peut comprendre des composants developpes par des
23  * tierces parties. Sun, Sun Microsystems, le logo Sun, Java et J2EE
24  * sont des marques de fabrique ou des marques deposees de Sun
25  * Microsystems, Inc. aux Etats-Unis et dans d'autres pays.
26  */

27
28 package bank;
29
30 import java.math.BigDecimal JavaDoc;
31 import java.sql.Connection JavaDoc;
32 import java.sql.PreparedStatement JavaDoc;
33 import java.sql.ResultSet JavaDoc;
34 import java.sql.SQLException JavaDoc;
35 import java.util.ArrayList JavaDoc;
36 import java.util.Collection JavaDoc;
37 import java.util.Iterator JavaDoc;
38 import javax.ejb.*;
39
40 /**
41  * This is the bean class for the SavingsAccountBean enterprise bean.
42  * Created Mar 23, 2005 12:58:37 PM
43  * @author blaha
44  */

45 public class SavingsAccountBean implements EntityBean, SavingsAccountRemoteBusiness {
46     private EntityContext context;
47     private Connection JavaDoc con;
48     private String JavaDoc id;
49     private String JavaDoc firstName;
50     private String JavaDoc lastName;
51     private BigDecimal JavaDoc balance;
52     
53     // <editor-fold defaultstate="collapsed" desc="EJB infrastructure methods. Click the + sign on the left to edit the code.">
54
// TODO Add code to acquire and use other enterprise resources (DataSource, JMS, enterprise beans, Web services)
55
// TODO Add business methods
56
// TODO Add create methods
57
/**
58      * @see javax.ejb.EntityBean#setEntityContext(javax.ejb.EntityContext)
59      */

60     public void setEntityContext(EntityContext aContext) {
61         context = aContext;
62     }
63     
64     /**
65      * @see javax.ejb.EntityBean#ejbActivate()
66      */

67     public void ejbActivate() {
68         id = (String JavaDoc)context.getPrimaryKey();
69     }
70     
71     /**
72      * @see javax.ejb.EntityBean#ejbPassivate()
73      */

74     public void ejbPassivate() {
75         id = null;
76     }
77     
78     /**
79      * @see javax.ejb.EntityBean#ejbRemove()
80      */

81     public void ejbRemove() {
82         try{
83             deleteRow(id);
84         }catch(SQLException JavaDoc ex){
85             throw new EJBException("ejbRemove: " + ex.getMessage());
86         }
87     }
88     
89     /**
90      * @see javax.ejb.EntityBean#unsetEntityContext()
91      */

92     public void unsetEntityContext() {
93         context = null;
94     }
95     
96     /**
97      * @see javax.ejb.EntityBean#ejbLoad()
98      */

99     public void ejbLoad() {
100         // TODO add code to retrieve data
101
try{
102         loadRow();
103         }catch(SQLException JavaDoc ex){
104             throw new EJBException("ejbLoad() " + ex.getMessage());
105         }
106             
107     }
108     
109     /**
110      * @see javax.ejb.EntityBean#ejbStore()
111      */

112     public void ejbStore() {
113         // TODO add code to persist data
114
try{
115         storeRow();
116         }catch(SQLException JavaDoc ex){
117             throw new EJBException("ejbStore " + ex.getMessage());
118         }
119     }
120     
121     // </editor-fold>
122

123     /**
124      * See EJB 2.0 and EJB 2.1 section 12.2.5
125      */

126     public java.lang.String JavaDoc ejbFindByPrimaryKey(java.lang.String JavaDoc aKey) throws FinderException {
127         // TODO add code to locate aKey from persistent storage
128
// throw javax.ejb.ObjectNotFoundException if aKey is not in
129
// persistent storage.
130
boolean result;
131         try{
132             result = selectByPrimaryKey(aKey);
133         }catch(SQLException JavaDoc ex){
134             throw new EJBException("ejbFindByPrimaryKey: " + ex.getMessage());
135         }
136         if(result){
137             return aKey;
138         }else{
139             throw new ObjectNotFoundException("Account for id " + aKey + " not found.");
140         }
141     }
142     
143     public java.lang.String JavaDoc ejbCreate(java.lang.String JavaDoc id, java.lang.String JavaDoc firstName, java.lang.String JavaDoc lastName, java.math.BigDecimal JavaDoc balance) throws CreateException {
144         //TODO implement ejbCreate
145
if(balance.signum() == -1){
146             throw new CreateException("A negative initial balance is not allowed.");
147         }
148         try{
149             insertRow(id, firstName, lastName, balance);
150         }catch(SQLException JavaDoc ex){
151             throw new EJBException("ejbCreate: " + ex.getMessage());
152         }
153         this.id = id;
154         this.firstName = firstName;
155         this.lastName = lastName;
156         this.balance = balance;
157         return id;
158     }
159     
160     public void ejbPostCreate(java.lang.String JavaDoc id, java.lang.String JavaDoc firstName, java.lang.String JavaDoc lastName, java.math.BigDecimal JavaDoc balance) throws CreateException {
161         //TODO implement ejbPostCreate
162
}
163     
164     private javax.sql.DataSource JavaDoc getSavingsAccountDB() throws javax.naming.NamingException JavaDoc {
165         javax.naming.Context JavaDoc c = new javax.naming.InitialContext JavaDoc();
166         return (javax.sql.DataSource JavaDoc) c.lookup("java:comp/env/jdbc/pointbase");
167     }
168     
169     public String JavaDoc getId() {
170         return id;
171     }
172     
173     public void setId(String JavaDoc id) {
174         this.id = id;
175     }
176     
177     public String JavaDoc getFirstName() {
178         return firstName;
179     }
180     
181     public void setFirstName(String JavaDoc firstName) {
182         this.firstName = firstName;
183     }
184     
185     public String JavaDoc getLastName() {
186         return lastName;
187     }
188     
189     public void setLastName(String JavaDoc lastName) {
190         this.lastName = lastName;
191     }
192     
193     public BigDecimal JavaDoc getBalance() {
194         return balance;
195     }
196     
197     public void setBalance(BigDecimal JavaDoc balance) {
198         this.balance = balance;
199     }
200     
201     public void credit(BigDecimal JavaDoc credit){
202         balance = balance.add(credit);
203     }
204     
205     // business method
206
public void debit(BigDecimal JavaDoc amount) throws InsufficientBalanceException {
207         if (balance.compareTo(amount) == -1) {
208             throw new InsufficientBalanceException();
209         }
210                                                                                             
211         balance = balance.subtract(amount);
212     }
213     
214     private void makeConnection(){
215         try{
216             con = getSavingsAccountDB().getConnection();
217         }catch(Exception JavaDoc ex){
218             throw new EJBException("Unable to connect to database. " +
219                     ex.getMessage());
220         }
221     }
222     
223     private void releaseConnection(){
224         try{
225             con.close();
226         }catch(SQLException JavaDoc ex){
227             throw new EJBException("Unable to connect to database. " +
228                     ex.getMessage());
229         }
230     }
231     
232     // finder methods
233

234     public java.util.Collection JavaDoc ejbFindInRange(BigDecimal JavaDoc low, BigDecimal JavaDoc high) throws FinderException {
235         //TODO implement ejbFindByInRange
236
Collection JavaDoc result;
237          try{
238           result = selectInRange(low, high);
239          }catch(SQLException JavaDoc ex){
240              throw new EJBException("ejbFindByInRange" + ex.getMessage());
241          }
242         return result;
243     }
244
245     public java.util.Collection JavaDoc ejbFindByLastName(java.lang.String JavaDoc lastName) throws FinderException {
246         //TODO implement ejbFindByLastName
247
Collection JavaDoc result;
248          try{
249           result = selectByLastName(lastName);
250          }catch(SQLException JavaDoc ex){
251              throw new EJBException("ejbFindByLastName" + ex.getMessage());
252          }
253         return result;
254     }
255     
256     // home method
257
public void ejbHomeChargeForLowBalance(BigDecimal JavaDoc minimumBalance,
258         BigDecimal JavaDoc charge) throws InsufficientBalanceException {
259         SavingsAccountRemoteHome home = (SavingsAccountRemoteHome)context.getEJBHome();
260         try{
261         Collection JavaDoc c =
262                 home.findInRange(new BigDecimal JavaDoc(0.00),
263                 minimumBalance.subtract(new BigDecimal JavaDoc(0.01)));
264         Iterator JavaDoc it = c.iterator();
265         while(it.hasNext()){
266             SavingsAccountRemote account = (SavingsAccountRemote)it.next();
267             if(account.getBalance().compareTo(charge) == 1){
268                 account.debit(charge);
269             }
270         }
271         }catch(Exception JavaDoc ex){
272             throw new EJBException("ejbHomeChargeForLowBalance" + ex.getMessage());
273         }
274     }
275
276     // database methods
277

278     private void insertRow(String JavaDoc id, String JavaDoc firstName,
279             String JavaDoc lastName, BigDecimal JavaDoc balance) throws SQLException JavaDoc{
280         makeConnection();
281         String JavaDoc insertStatement = "insert into savingsaccount values ( ? , ? , ? , ? )";
282         PreparedStatement JavaDoc prepStmt = con.prepareStatement(insertStatement);
283         
284         prepStmt.setString(1, id);
285         prepStmt.setString(2, firstName);
286         prepStmt.setString(3, lastName);
287         prepStmt.setBigDecimal(4, balance);
288         
289         prepStmt.executeUpdate();
290         prepStmt.close();
291         releaseConnection();
292     }
293     
294     private void deleteRow(String JavaDoc id) throws SQLException JavaDoc {
295         makeConnection();
296         String JavaDoc deleteStatement = "delete from savingsaccount where id = ?";
297         PreparedStatement JavaDoc prepStmt = con.prepareStatement(deleteStatement);
298         prepStmt.setString(1, id);
299         prepStmt.executeUpdate();
300         prepStmt.close();
301         releaseConnection();
302     }
303     
304     private boolean selectByPrimaryKey(String JavaDoc id) throws SQLException JavaDoc{
305         makeConnection();
306         String JavaDoc selectStatement = "select id from savingsaccount where id = ?";
307         PreparedStatement JavaDoc prepStmt = con.prepareStatement(selectStatement);
308         prepStmt.setString(1, id);
309         
310         ResultSet JavaDoc rs = prepStmt.executeQuery();
311         boolean result = rs.next();
312         
313         releaseConnection();
314         return result;
315     }
316     
317     private void loadRow() throws SQLException JavaDoc{
318         makeConnection();
319         String JavaDoc selectString =
320                 "select firstname, lastname, balance from savingsaccount where id = ?";
321         PreparedStatement JavaDoc prepStmt = con.prepareStatement(selectString);
322         prepStmt.setString(1, this.id);
323         ResultSet JavaDoc rs = prepStmt.executeQuery();
324         
325         if(rs.next()){
326             this.firstName = rs.getString(1);
327             this.lastName = rs.getString(2);
328             this.balance = rs.getBigDecimal(3);
329             prepStmt.close();
330         }else {
331             prepStmt.close();
332             throw new NoSuchEntityException("Row for id " + id +
333                     " not found in database");
334         }
335         
336         releaseConnection();
337     }
338     
339     private void storeRow() throws SQLException JavaDoc {
340         makeConnection();
341         String JavaDoc updateString =
342                 "update savingsaccount set firstname = ? , lastname = ? , " +
343                 "balance = ? where id = ?";
344         PreparedStatement JavaDoc prepStmt = con.prepareStatement(updateString);
345         prepStmt.setString(1, firstName);
346         prepStmt.setString(2, lastName);
347         prepStmt.setBigDecimal(3, balance);
348         prepStmt.setString(4, id);
349         
350         int rows = prepStmt.executeUpdate();
351         prepStmt.close();
352         releaseConnection();
353         if(rows == 0){
354             throw new EJBException("Storing row id " + id + " failed.");
355         }
356     }
357     
358     private Collection JavaDoc selectByLastName(String JavaDoc lastName) throws SQLException JavaDoc{
359         makeConnection();
360         String JavaDoc selectStatement = "select id from savingsaccount where lastname = ?";
361         PreparedStatement JavaDoc prepStmt = con.prepareStatement(selectStatement);
362         prepStmt.setString(1, lastName);
363         ResultSet JavaDoc rs = prepStmt.executeQuery();
364         ArrayList JavaDoc accounts = new ArrayList JavaDoc();
365         
366          while(rs.next()){
367             accounts.add(rs.getString(1));
368          }
369         prepStmt.close();
370         releaseConnection();
371         return accounts;
372     }
373     
374     private Collection JavaDoc selectInRange(BigDecimal JavaDoc low, BigDecimal JavaDoc high) throws SQLException JavaDoc {
375         makeConnection();
376         String JavaDoc selectStatement = "select id from savingsaccount where balance between ? and ?";
377         PreparedStatement JavaDoc prepStmt = con.prepareStatement(selectStatement);
378         prepStmt.setBigDecimal(1, low);
379         prepStmt.setBigDecimal(2, high);
380         
381         ResultSet JavaDoc rs = prepStmt.executeQuery();
382         ArrayList JavaDoc a = new ArrayList JavaDoc();
383         
384         while(rs.next()){
385             a.add(rs.getString(1));
386         }
387         prepStmt.close();
388         releaseConnection();
389         return a;
390     }
391 }
392
Popular Tags