KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > test > cts > ejb > CtsBmpBean


1 /*
2   * JBoss, Home of Professional Open Source
3   * Copyright 2005, JBoss Inc., and individual contributors as indicated
4   * by the @authors tag. See the copyright.txt in the distribution for a
5   * full listing of individual contributors.
6   *
7   * This is free software; you can redistribute it and/or modify it
8   * under the terms of the GNU Lesser General Public License as
9   * published by the Free Software Foundation; either version 2.1 of
10   * the License, or (at your option) any later version.
11   *
12   * This software is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   * Lesser General Public License for more details.
16   *
17   * You should have received a copy of the GNU Lesser General Public
18   * License along with this software; if not, write to the Free
19   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21   */

22 package org.jboss.test.cts.ejb;
23
24 import java.util.Collection JavaDoc;
25
26 import javax.sql.DataSource JavaDoc;
27 import java.sql.Connection JavaDoc;
28 import java.sql.Statement JavaDoc;
29 import java.sql.PreparedStatement JavaDoc;
30 import java.sql.ResultSet JavaDoc;
31 import java.sql.ResultSetMetaData JavaDoc;
32 import java.sql.Types JavaDoc;
33 import java.sql.SQLException JavaDoc;
34
35 import javax.naming.InitialContext JavaDoc;
36 import javax.naming.Context JavaDoc;
37 import javax.naming.NamingException JavaDoc;
38
39 import javax.jms.JMSException JavaDoc;
40 import javax.ejb.EntityBean JavaDoc;
41 import javax.ejb.EntityContext JavaDoc;
42 import javax.ejb.CreateException JavaDoc;
43 import javax.ejb.DuplicateKeyException JavaDoc;
44 import javax.ejb.FinderException JavaDoc;
45 import javax.ejb.ObjectNotFoundException JavaDoc;
46 import javax.ejb.NoSuchEntityException JavaDoc;
47 import javax.ejb.EJBException JavaDoc;
48
49 import org.jboss.test.cts.keys.AccountPK;
50
51 import org.jboss.test.cts.jms.ContainerMBox;
52 import org.jboss.test.cts.jms.MsgSender;
53
54 /**
55  * Class CtsBmpBean is a simple BMP entity bean for testing.
56  * <p/>
57  * If the table used for persistence here does not exist, ejbFindAll()
58  * will create it.
59  *
60  * @author $Author: scott.stark@jboss.org $
61  * @version $Revision: 58115 $
62  */

63
64 public class CtsBmpBean
65    implements EntityBean JavaDoc
66 {
67    org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(getClass());
68
69    private static final String JavaDoc TABLE_NAME = "BMP_BEAN_TBL";
70    EntityContext JavaDoc ctx = null;
71    DataSource JavaDoc ds = null;
72
73    private MsgSender ms = null;
74
75    // bmp fields
76
String JavaDoc accountNumber;
77    String JavaDoc personsName;
78
79    /**
80     * Create a new instance.
81     *
82     * @param pk The primary key of the new instance.
83     * @param personsName Person name of the new instance.
84     * @throws CreateException In case of database row creation failure.
85     * @throws DuplicateKeyException If another instance with this primary key already exist.
86     */

87    public AccountPK ejbCreate(AccountPK pk, String JavaDoc personsName)
88       throws CreateException JavaDoc, DuplicateKeyException JavaDoc
89    {
90       log.debug("entry ejbCreate(\"" + pk.getKey() + "\", " +
91          "\"" + personsName + "\")");
92
93       sendMsg(ContainerMBox.EJB_CREATE_MSG);
94
95       try
96       {
97          Connection JavaDoc con = ds.getConnection();
98          try
99          {
100             PreparedStatement JavaDoc ps;
101  
102             // Check for duplicates.
103
ps = con.prepareStatement("SELECT accountNumber " +
104                "FROM " + TABLE_NAME + " " +
105                "WHERE accountNumber=?");
106             try
107             {
108                ps.setString(1, pk.getKey());
109
110                ResultSet JavaDoc rs = ps.executeQuery();
111
112                if (rs.next())
113                   throw new DuplicateKeyException JavaDoc("Bean with accountNumber=" +
114                      pk.getKey() +
115                      " already exists.");
116             }
117             finally
118             {
119                ps.close();
120             }
121  
122             // Create in database.
123
ps = con.prepareStatement("INSERT INTO " + TABLE_NAME +
124                " VALUES (?,?)");
125             try
126             {
127                ps.setString(1, pk.getKey());
128                ps.setString(2, personsName);
129
130                ps.execute();
131             }
132             finally
133             {
134                ps.close();
135             }
136          }
137          finally
138          {
139             con.close();
140          }
141       }
142       catch (SQLException JavaDoc e)
143       {
144          log.debug("failed", e);
145
146          throw new CreateException JavaDoc("Entity bean creation failure: " +
147             e.getMessage());
148       }
149
150       this.accountNumber = pk.getKey();
151       this.personsName = personsName;
152
153       log.debug("Created \"" + accountNumber + "\".");
154
155       return pk;
156    }
157
158    /**
159     * Method ejbPostCreate
160     */

161    public void ejbPostCreate(AccountPK pk, String JavaDoc personsName)
162    {
163       log.debug("ejbPostCreate(AccountPK, String) called");
164
165       sendMsg(ContainerMBox.EJB_POST_CREATE_MSG);
166    }
167
168    /**
169     * Find a single instance by primary key.
170     *
171     * @param pk Primary key of the instance searched for.
172     * @throws ObjectNotFoundException If no instance with this primary key exists.
173     * @throws FinderException If the lookup failed.
174     */

175    public AccountPK ejbFindByPrimaryKey(AccountPK pk)
176       throws FinderException JavaDoc
177    {
178       log.debug("entry ejbFindByPrimaryKey");
179
180       try
181       {
182          Connection JavaDoc con = ds.getConnection();
183          try
184          {
185             PreparedStatement JavaDoc ps;
186
187             ps = con.prepareStatement("SELECT accountNumber " +
188                "FROM " + TABLE_NAME + " " +
189                "WHERE accountNumber=?");
190             try
191             {
192                ps.setString(1, pk.getKey());
193
194                ResultSet JavaDoc rs = ps.executeQuery();
195
196                if (!rs.next())
197                   throw new ObjectNotFoundException JavaDoc("No bean with " +
198                      "accountNumber=" +
199                      pk.getKey() + " found.");
200
201                return pk;
202             }
203             finally
204             {
205                ps.close();
206             }
207          }
208          finally
209          {
210             con.close();
211          }
212       }
213       catch (SQLException JavaDoc e)
214       {
215          log.debug("failed", e);
216
217          throw new FinderException JavaDoc("Could not find: " + e.getMessage());
218       }
219    }
220
221    /**
222     * Find all instances.
223     *
224     * @throws FinderException If the lookup failed.
225     */

226    public Collection JavaDoc ejbFindAll()
227       throws FinderException JavaDoc
228    {
229       log.debug("entry ejbFindAll");
230
231       ensureTableExists();
232
233       Collection JavaDoc result = new java.util.LinkedList JavaDoc();
234       try
235       {
236          Connection JavaDoc con = ds.getConnection();
237          try
238          {
239             PreparedStatement JavaDoc ps;
240
241             ps = con.prepareStatement("SELECT accountNumber " +
242                "FROM " + TABLE_NAME);
243             try
244             {
245                ResultSet JavaDoc rs = ps.executeQuery();
246
247                while (rs.next())
248                   result.add(new AccountPK(rs.getString(1)));
249
250                return result;
251             }
252             finally
253             {
254                ps.close();
255             }
256          }
257          finally
258          {
259             con.close();
260          }
261       }
262       catch (SQLException JavaDoc e)
263       {
264          log.debug("failed", e);
265
266          throw new FinderException JavaDoc("Could not find: " + e.getMessage());
267       }
268    }
269
270    /**
271     * Find all instances where the personsName property is
272     * equal to the argument.
273     *
274     * @throws FinderException If the lookup failed.
275     */

276    public Collection JavaDoc ejbFindByPersonsName(String JavaDoc guysName)
277       throws FinderException JavaDoc
278    {
279       log.debug("entry ejbFindByPersonsName(\"" + guysName + "\").");
280
281       Collection JavaDoc result = new java.util.LinkedList JavaDoc();
282       try
283       {
284          Connection JavaDoc con = ds.getConnection();
285          try
286          {
287             PreparedStatement JavaDoc ps;
288
289             ps = con.prepareStatement("SELECT accountNumber " +
290                "FROM " + TABLE_NAME + " " +
291                "WHERE name=?");
292             try
293             {
294                ps.setString(1, guysName);
295
296                ResultSet JavaDoc rs = ps.executeQuery();
297
298                while (rs.next())
299                   result.add(new AccountPK(rs.getString(1)));
300
301                return result;
302             }
303             finally
304             {
305                ps.close();
306             }
307          }
308          finally
309          {
310             con.close();
311          }
312       }
313       catch (SQLException JavaDoc e)
314       {
315          log.debug("failed", e);
316
317          throw new FinderException JavaDoc("Could not find: " + e.getMessage());
318       }
319    }
320
321    /**
322     * Method ejbLoad
323     */

324    public void ejbLoad()
325    {
326       log.debug("ejbLoad(\"" +
327          ((AccountPK) ctx.getPrimaryKey()).getKey() +
328          "\") called");
329
330       sendMsg(ContainerMBox.EJB_LOAD_MSG);
331
332       try
333       {
334          Connection JavaDoc con = ds.getConnection();
335          try
336          {
337             PreparedStatement JavaDoc ps;
338
339             ps = con.prepareStatement("SELECT accountNumber,name " +
340                "FROM " + TABLE_NAME + " " +
341                "WHERE accountNumber=?");
342             try
343             {
344                AccountPK pk = (AccountPK) ctx.getPrimaryKey();
345
346                ps.setString(1, pk.getKey());
347                ResultSet JavaDoc rs = ps.executeQuery();
348
349                if (rs.next() == false)
350                   throw new NoSuchEntityException JavaDoc("Instance " + pk.getKey() +
351                      " not found in database.");
352
353                accountNumber = rs.getString(1);
354                personsName = rs.getString(2);
355             }
356             finally
357             {
358                ps.close();
359             }
360          }
361          finally
362          {
363             con.close();
364          }
365       }
366       catch (SQLException JavaDoc e)
367       {
368          log.debug("failed", e);
369
370          throw new EJBException JavaDoc(e);
371       }
372
373       log.debug("ejbLoad(\"" +
374          ((AccountPK) ctx.getPrimaryKey()).getKey() +
375          "\") returning");
376
377    }
378
379    /**
380     * Method ejbStore
381     */

382    public void ejbStore()
383    {
384       log.debug("ejbStore(\"" + accountNumber + "\") called");
385 //Thread.currentThread().dumpStack();
386

387       sendMsg(ContainerMBox.EJB_STORE_MSG);
388
389       try
390       {
391          Connection JavaDoc con = ds.getConnection();
392          try
393          {
394             PreparedStatement JavaDoc ps;
395
396             ps = con.prepareStatement("UPDATE " + TABLE_NAME + " " +
397                "SET name=? " +
398                "WHERE accountNumber=?");
399             try
400             {
401                ps.setString(1, personsName);
402                ps.setString(2, accountNumber);
403
404                ps.executeUpdate();
405             }
406             finally
407             {
408                ps.close();
409             }
410          }
411          finally
412          {
413             con.close();
414          }
415       }
416       catch (SQLException JavaDoc e)
417       {
418          log.debug("failed", e);
419
420          throw new EJBException JavaDoc(e);
421       }
422
423       log.debug("ejbStore(\"" + accountNumber + "\") returning");
424    }
425
426    /**
427     * Method ejbRemove
428     */

429    public void ejbRemove()
430    {
431       log.debug("ejbRemove(\"" + accountNumber + "\") called");
432
433       sendMsg(ContainerMBox.EJB_REMOVE_MSG);
434
435       try
436       {
437          Connection JavaDoc con = ds.getConnection();
438          try
439          {
440             PreparedStatement JavaDoc ps;
441
442             ps = con.prepareStatement("DELETE FROM " + TABLE_NAME + " " +
443                "WHERE accountNumber=?");
444             try
445             {
446                ps.setString(1, accountNumber);
447
448                ps.executeUpdate();
449             }
450             finally
451             {
452                ps.close();
453             }
454          }
455          finally
456          {
457             con.close();
458          }
459       }
460       catch (SQLException JavaDoc e)
461       {
462          log.debug("failed", e);
463
464          throw new EJBException JavaDoc(e);
465       }
466
467       log.debug("Removed \"" + accountNumber + "\".");
468    }
469
470    /**
471     * Method ejbActivate
472     */

473    public void ejbActivate()
474    {
475       log.debug("ejbActivate() called");
476
477       sendMsg(ContainerMBox.EJB_ACTIVATE_MSG);
478    }
479
480    /**
481     * Method ejbPassivate
482     */

483    public void ejbPassivate()
484    {
485       log.debug("ejbPassivate() called");
486
487       sendMsg(ContainerMBox.EJB_PASSIVATE_MSG);
488
489       // drop message sender
490
if (ms != null)
491       {
492          try
493          {
494             ms.close();
495          }
496          catch (JMSException JavaDoc e)
497          {
498             log.debug("failed", e);
499             // otherwise ignore
500
}
501          ms = null;
502       }
503    }
504
505    /**
506     * Method setEntityContext
507     */

508    public void setEntityContext(EntityContext JavaDoc ctx)
509    {
510       log.debug("setEntityContext() called");
511
512       sendMsg(ContainerMBox.SET_ENTITY_CONTEXT_MSG);
513
514       this.ctx = ctx;
515
516       // lookup the datasource
517
try
518       {
519          Context JavaDoc context = new InitialContext JavaDoc();
520
521          ds = (DataSource JavaDoc) context.lookup("java:comp/env/datasource");
522       }
523       catch (NamingException JavaDoc nex)
524       {
525          log.debug("failed", nex);
526
527          throw new EJBException JavaDoc("Datasource not found: " + nex.getMessage());
528       }
529    }
530
531    /**
532     * Method unsetEntityContext
533     */

534    public void unsetEntityContext()
535    {
536       log.debug("unsetEntityContext() called");
537
538       sendMsg(ContainerMBox.UNSET_ENTITY_CONTEXT_MSG);
539
540       ctx = null;
541       ds = null;
542    }
543
544
545    //
546
// Private methods
547
//
548

549    /**
550     * Check if a good table exists, and create it if needed.
551     */

552    private void ensureTableExists()
553    {
554       boolean exists = true;
555
556       try
557       {
558          Connection JavaDoc con = ds.getConnection();
559          try
560          {
561             Statement JavaDoc s = con.createStatement();
562             try
563             {
564                ResultSet JavaDoc rs = s.executeQuery("SELECT * FROM " + TABLE_NAME);
565                ResultSetMetaData JavaDoc md = rs.getMetaData();
566
567                if (md.getColumnCount() != 2)
568                   throw new SQLException JavaDoc("Not two columns");
569
570                if (!"ACCOUNTNUMBER".equals(md.getColumnName(1).toUpperCase()))
571                   throw new SQLException JavaDoc("First column name not \"accountNumber\"");
572                if (!"NAME".equals(md.getColumnName(2).toUpperCase()))
573                   throw new SQLException JavaDoc("Second column name not \"name\"");
574
575                if (md.getColumnType(1) != Types.VARCHAR)
576                   throw new SQLException JavaDoc("First column type not VARCHAR");
577                if (md.getColumnType(2) != Types.VARCHAR)
578                   throw new SQLException JavaDoc("Second column type not VARCHAR");
579             }
580             finally
581             {
582                s.close();
583             }
584          }
585          finally
586          {
587             con.close();
588          }
589       }
590       catch (SQLException JavaDoc e)
591       {
592          exists = false;
593       }
594
595       if (!exists)
596          initializeDatabaseTable();
597    }
598
599    /**
600     * Create the table, removing any old table first.
601     */

602    private void initializeDatabaseTable()
603    {
604       log.debug("Initializing DATABASE tables for BMP test...");
605
606       try
607       {
608          Connection JavaDoc con = ds.getConnection();
609          try
610          {
611             Statement JavaDoc s;
612
613             s = con.createStatement();
614             try
615             {
616                s.executeUpdate("DROP TABLE " + TABLE_NAME);
617                log.debug("Dropped old table.");
618             }
619             catch (SQLException JavaDoc e)
620             {
621                // Ignore: Presume the table didn't exist.
622
}
623             finally
624             {
625                s.close();
626             }
627
628             s = con.createStatement();
629             try
630             {
631                s.executeUpdate("CREATE TABLE " + TABLE_NAME + " " +
632                   "(accountNumber VARCHAR(25)," +
633                   " name VARCHAR(200))");
634                log.debug("Created new table.");
635             }
636             finally
637             {
638                s.close();
639             }
640          }
641          finally
642          {
643             con.close();
644          }
645       }
646       catch (SQLException JavaDoc e)
647       {
648          log.debug("failed", e);
649
650          throw new EJBException JavaDoc(e);
651       }
652
653       log.debug("Initialized DATABASE tables for BMP test.");
654    }
655
656    /**
657     * Send a JMS message.
658     */

659    private void sendMsg(String JavaDoc msg)
660    {
661       if (ms == null)
662          ms = new MsgSender();
663
664       ms.sendMsg(msg);
665    }
666
667    //
668
// Business methods
669
//
670

671    /**
672     * Setter for property personsName.
673     */

674    public void setPersonsName(String JavaDoc personsName)
675    {
676       this.personsName = personsName;
677    }
678
679    /**
680     * Getter for property personsName.
681     */

682    public String JavaDoc getPersonsName()
683    {
684       return this.personsName;
685    }
686 }
687
688
Popular Tags