KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > test > entityexc > ejb > EntityExcBean


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.entityexc.ejb;
23
24 import java.util.Collection JavaDoc;
25
26 import java.rmi.RemoteException JavaDoc;
27
28 import javax.ejb.EntityBean JavaDoc;
29 import javax.ejb.EntityContext JavaDoc;
30 import javax.ejb.CreateException JavaDoc;
31 import javax.ejb.DuplicateKeyException JavaDoc;
32 import javax.ejb.FinderException JavaDoc;
33 import javax.ejb.ObjectNotFoundException JavaDoc;
34 import javax.ejb.NoSuchEntityException JavaDoc;
35 import javax.ejb.EJBException JavaDoc;
36
37 import javax.naming.InitialContext JavaDoc;
38 import javax.naming.Context JavaDoc;
39 import javax.naming.NamingException JavaDoc;
40
41 import java.sql.Connection JavaDoc;
42 import java.sql.PreparedStatement JavaDoc;
43 import java.sql.ResultSet JavaDoc;
44 import java.sql.SQLException JavaDoc;
45  
46 import javax.sql.DataSource JavaDoc;
47
48 import org.jboss.test.entityexc.interfaces.*;
49
50 /**
51  * Implementation of the ExtityExc EJB.
52  *
53  * @author <a HREF="mailto:osh@sparre.dk">Ole Husgaard</a>
54  * @version $Revision: 58115 $
55  */

56 public class EntityExcBean implements EntityBean JavaDoc
57 {
58     static org.jboss.logging.Logger log =
59        org.jboss.logging.Logger.getLogger(EntityExcBean.class);
60    
61    static final private boolean debug = true;
62
63    /**
64     * The entity context of this instance.
65     */

66    private EntityContext JavaDoc ctx;
67
68    /**
69     * Flags that this instance should have been discarded
70     * by the container.
71     */

72    private boolean wasDiscarded = false;
73
74    /**
75     * The primary key of this instance.
76     * The second instance property <code>value</code> is not
77     * stored here, but read and written on demand.
78     */

79    private int id;
80
81
82    /**
83     * Check if we are called when we should have been discarded.
84     */

85    private void checkDiscarded()
86    {
87       if (wasDiscarded) {
88          log.debug("**************************************************");
89          log.debug("Attempt to invoke method on an instance " +
90                             "that should have been discarded.");
91          log.debug("**************************************************");
92          throw new RuntimeException JavaDoc("Invokation on discarded instance");
93       }
94    }
95
96
97    private void doFailure(boolean isAfter, int flags)
98       throws MyAppException, CreateException JavaDoc
99    {
100       if (isAfter && (flags & EntityExc.F_SETROLLBACKONLY) != 0) {
101          if (debug)
102             log.debug("Marking transaction for rollback only.");
103          ctx.setRollbackOnly();
104       }
105
106       if ((flags & EntityExc.F_EXC_MASK) != 0) {
107          if (isAfter && (flags & EntityExc.F_THROW_BEFORE) != 0)
108             return;
109          if (!isAfter && (flags & EntityExc.F_THROW_BEFORE) == 0)
110             return;
111
112          switch (flags & EntityExc.F_EXC_MASK) {
113             case EntityExc.EXC_MYAPPEXCEPTION:
114                if (debug)
115                   log.debug("Throwing MyAppException");
116                throw new MyAppException(EntityExc.EXCEPTION_TEXT);
117             case EntityExc.EXC_CREATEEXCEPTION:
118                if (debug)
119                   log.debug("Throwing CreateException");
120                throw new CreateException JavaDoc(EntityExc.EXCEPTION_TEXT);
121             case EntityExc.EXC_EJBEXCEPTION:
122                if (debug)
123                   log.debug("Throwing EJBException");
124                wasDiscarded = true;
125                throw new EJBException JavaDoc(EntityExc.EXCEPTION_TEXT);
126             default:
127                wasDiscarded = true;
128                throw new EJBException JavaDoc("Unknown exception code.");
129          }
130       }
131    }
132
133    private void doFailureOnlyAppExc(boolean isAfter, int flags)
134       throws MyAppException
135    {
136       try {
137          doFailure(isAfter, flags);
138       } catch (CreateException JavaDoc ex) {
139          // should not happen
140
wasDiscarded = true;
141          throw new EJBException JavaDoc("Unexpected CreateException");
142       }
143    }
144
145    public void setEntityContext(EntityContext JavaDoc ctx)
146    {
147       if (debug)
148          log.debug("EntityExcBean.setEntityContext() entered.");
149
150       checkDiscarded();
151       this.ctx = ctx;
152    }
153
154    public void unsetEntityContext()
155    {
156       if (debug)
157          log.debug("EntityExcBean.unsetEntityContext() entered.");
158
159       checkDiscarded();
160       ctx = null;
161    }
162
163
164    public void ejbActivate()
165    {
166       if (debug)
167          log.debug("EntityExcBean.ejbActivate() entered.");
168
169       checkDiscarded();
170    }
171  
172    public void ejbPassivate()
173    {
174       if (debug)
175          log.debug("EntityExcBean.ejbPassivate() entered.");
176
177       checkDiscarded();
178    }
179
180
181    /**
182     * Get a reference to the environment of this enterprise bean.
183     */

184    protected Context JavaDoc getEnvironment()
185    {
186       try {
187          Context JavaDoc ic = new InitialContext JavaDoc();
188          return (Context JavaDoc)ic.lookup("java:comp/env");
189       } catch (NamingException JavaDoc ex) {
190          wasDiscarded = true;
191          throw new EJBException JavaDoc(ex);
192       }
193    }
194
195    /**
196     * Return the data source of this enterprise bean.
197     */

198    protected DataSource JavaDoc getDataSource()
199    {
200       try {
201          return (DataSource JavaDoc)getEnvironment().lookup("jdbc/entityexc");
202       } catch (NamingException JavaDoc ex) {
203          wasDiscarded = true;
204          throw new EJBException JavaDoc(ex);
205       }
206    }
207
208    private Integer JavaDoc ejbCreate(Integer JavaDoc pk)
209       throws CreateException JavaDoc
210    {
211       if (debug)
212          log.debug("EntityExcBean.ejbCreate(Integer pk=" +
213                           pk.intValue() + ") entered.");
214
215       this.id = pk.intValue();
216
217       try {
218          Connection JavaDoc conn = getDataSource().getConnection();
219          try {
220             PreparedStatement JavaDoc stmt;
221  
222             // Check for duplicate key
223
stmt = conn.prepareStatement("select id " +
224                                       "from entityexc " +
225                                       "where id=?");
226             try {
227               stmt.setInt(1, id);
228               ResultSet JavaDoc rs = stmt.executeQuery();
229               try {
230                  if (rs.next())
231                     throw new DuplicateKeyException JavaDoc("EntityExc id " + pk.intValue() +
232                                                     " already in database.");
233                } finally {
234                   rs.close();
235                }
236             } finally {
237                stmt.close();
238             }
239
240             stmt = conn.prepareStatement("insert into entityexc (id, val) " +
241                                       "values (?, ?)");
242             try {
243                stmt.setInt(1, id);
244                stmt.setInt(2, 0);
245                stmt.executeUpdate();
246             } finally {
247                stmt.close();
248             }
249  
250          } finally {
251             conn.close();
252          }
253       } catch (SQLException JavaDoc ex) {
254          wasDiscarded = true;
255          throw new EJBException JavaDoc(ex);
256       }
257
258       return pk;
259    }
260    
261    private void ejbPostCreate(Integer JavaDoc pk)
262    {
263       if (debug)
264          log.debug("EntityExcBean.ejbPostCreate(Integer pk=" +
265                             pk.intValue() + ") entered.");
266    }
267  
268    public Integer JavaDoc ejbCreate(Integer JavaDoc pk, int flags)
269       throws MyAppException, CreateException JavaDoc
270    {
271       if (debug)
272          log.debug("EntityExcBean.ejbCreate(Integer pk=" +
273                             pk.intValue() + ", int flags=0x" +
274                             Integer.toHexString(flags) + ") entered.");
275
276       checkDiscarded();
277
278       if ((flags & EntityExc.F_FAIL_POSTCREATE) == 0)
279          doFailure(false, flags);
280
281       Integer JavaDoc pk2 = ejbCreate(pk);
282
283       if ((flags & EntityExc.F_FAIL_POSTCREATE) == 0)
284          doFailure(true, flags);
285
286       return pk2;
287    }
288
289    public void ejbPostCreate(Integer JavaDoc pk, int flags)
290       throws MyAppException, CreateException JavaDoc
291    {
292       if (debug)
293          log.debug("EntityExcBean.ejbPostCreate(Integer pk=" +
294                             pk.intValue() + ", int flags=" +
295                             Integer.toHexString(flags) + ") entered.");
296
297       checkDiscarded();
298
299 log.debug("#1");
300       if ((flags & EntityExc.F_FAIL_POSTCREATE) != 0)
301          doFailure(false, flags);
302
303 log.debug("#2");
304       if ((flags & EntityExc.F_FAIL_POSTCREATE) != 0)
305          doFailure(true, flags);
306 log.debug("#3");
307    }
308  
309
310    public void ejbRemove()
311    {
312       if (debug)
313          log.debug("EntityExcBean.ejbRemove() entered.");
314
315       try {
316          Connection JavaDoc conn = getDataSource().getConnection();
317          try {
318             PreparedStatement JavaDoc stmt;
319  
320             stmt = conn.prepareStatement("delete from entityexc " +
321                                          "where id=?");
322             try {
323                stmt.setInt(1, id);
324                stmt.executeUpdate();
325             } finally {
326                stmt.close();
327             }
328          } finally {
329             conn.close();
330          }
331       } catch (SQLException JavaDoc ex) {
332          wasDiscarded = true;
333          throw new EJBException JavaDoc(ex);
334       }
335    }
336
337
338    private Integer JavaDoc ejbFindByPrimaryKey(Integer JavaDoc pk)
339       throws FinderException JavaDoc
340    {
341       if (debug)
342          log.debug("EntityExcBean.ejbFindByPrimaryKey(Integer pk=" +
343                             pk.intValue() + ") entered.");
344
345       try {
346          Connection JavaDoc conn = getDataSource().getConnection();
347          try {
348             PreparedStatement JavaDoc stmt;
349  
350             stmt = conn.prepareStatement("select id from entityexc where id=?");
351             try {
352                stmt.setInt(1, pk.intValue());
353                ResultSet JavaDoc rs = stmt.executeQuery();
354                try {
355                   if (!rs.next())
356                      throw new ObjectNotFoundException JavaDoc
357                ("EntityExc id " + pk.intValue() + " not found in database.");
358                } finally {
359                   rs.close();
360                }
361             } finally {
362                stmt.close();
363             }
364          } finally {
365             conn.close();
366          }
367       } catch (SQLException JavaDoc e) {
368          throw new FinderException JavaDoc("Failed to execute query " +e);
369       }
370  
371       return pk;
372    }
373
374    public Integer JavaDoc ejbFindByPrimaryKey(Integer JavaDoc pk, int flags)
375       throws MyAppException, FinderException JavaDoc
376    {
377       if (debug)
378          log.debug("EntityExcBean.ejbFindByPrimaryKey(Integer pk=" +
379                             pk.intValue() + ", int flags=0x" +
380                             Integer.toHexString(flags) + ") entered.");
381
382       checkDiscarded();
383
384       doFailureOnlyAppExc(false, flags);
385
386       Integer JavaDoc pk2 = ejbFindByPrimaryKey(pk);
387
388       doFailureOnlyAppExc(true, flags);
389
390       return pk2;
391    }
392
393    private Collection JavaDoc ejbFindAll()
394       throws FinderException JavaDoc
395    {
396       if (debug)
397           log.debug("EntityExcBean.ejbFindAll() entered.");
398
399       Collection JavaDoc c = new java.util.LinkedList JavaDoc();
400       try {
401          Connection JavaDoc conn = getDataSource().getConnection();
402          try {
403             PreparedStatement JavaDoc stmt;
404  
405             stmt = conn.prepareStatement("select id from entityexc");
406             try {
407                ResultSet JavaDoc rs = stmt.executeQuery();
408                try {
409                   while (rs.next())
410                      c.add(new Integer JavaDoc(rs.getInt(1)));
411                } finally {
412                   rs.close();
413                }
414             } finally {
415                stmt.close();
416             }
417          } finally {
418             conn.close();
419          }
420       } catch (SQLException JavaDoc ex) {
421          throw new FinderException JavaDoc("Failed to execute query " + ex);
422       }
423  
424       return c;
425    }
426
427    public Collection JavaDoc ejbFindAll(int flags)
428       throws MyAppException, FinderException JavaDoc
429    {
430       if (debug)
431          log.debug("EntityExcBean.ejbFindAll(int flags=0x" +
432                             Integer.toHexString(flags) + ") entered.");
433
434       checkDiscarded();
435
436       doFailureOnlyAppExc(false, flags);
437
438       Collection JavaDoc c = ejbFindAll();
439
440       doFailureOnlyAppExc(true, flags);
441
442       return c;
443    }
444
445    public void ejbLoad() {
446       if (debug)
447          log.debug("EntityExcBean.ejbLoad() entered.");
448
449       checkDiscarded();
450
451       Object JavaDoc key = ctx.getPrimaryKey();
452       if (key == null)
453          log.debug("EntityExcBean.ejbLoad(): " +
454                             "ctx.getPrimaryKey() returned null.");
455       else
456          log.debug("EntityExcBean.ejbLoad(): " +
457                             "ctx.getPrimaryKey() returned class " +
458                             key.getClass().getName());
459
460       id = ((Integer JavaDoc)ctx.getPrimaryKey()).intValue();
461    }
462
463    public void ejbStore() {
464       if (debug)
465          log.debug("EntityExcBean.ejbStore() entered.");
466
467       checkDiscarded();
468    }
469
470
471    public void ejbHomeResetDatabase()
472    {
473       try {
474          Connection JavaDoc conn = getDataSource().getConnection();
475          try {
476             log.debug("Creating database table entityexc.");
477
478             PreparedStatement JavaDoc stmt;
479  
480             stmt = conn.prepareStatement("drop table entityexc");
481             try {
482                stmt.executeUpdate();
483             } finally {
484                stmt.close();
485             }
486             log.debug("Database table entityexc dropped.");
487          } finally {
488             conn.close();
489          }
490       } catch (SQLException JavaDoc ex) {
491          log.debug("Ignoring error dropping database table: " + ex);
492       }
493       try {
494          Connection JavaDoc conn = getDataSource().getConnection();
495          try {
496             log.debug("Creating database table entityexc.");
497
498             PreparedStatement JavaDoc stmt;
499  
500             stmt = conn.prepareStatement("create table entityexc" +
501                                          " (id integer, val integer)");
502             try {
503                stmt.executeUpdate();
504             } finally {
505                stmt.close();
506             }
507             log.debug("Database table entityexc created.");
508          } finally {
509             conn.close();
510          }
511       } catch (SQLException JavaDoc ex) {
512          log.debug("Error creating database table: " + ex);
513          wasDiscarded = true;
514          throw new EJBException JavaDoc("Error creating database table: " + ex);
515       }
516    }
517
518
519    //
520
// Business method helpers.
521
//
522

523    /**
524     * Read the <code>val</code> property from the database,
525     * using the given connection.
526     */

527    private int get_val(Connection JavaDoc conn)
528       throws SQLException JavaDoc
529    {
530       if (debug)
531          log.debug("EntityExcBean.get_val() entered.");
532
533       PreparedStatement JavaDoc stmt = conn.prepareStatement("select val " +
534                                                      "from entityexc " +
535                                                      "where id=?");
536       try {
537          stmt.setInt(1, id);
538          ResultSet JavaDoc rs = stmt.executeQuery();
539          try {
540             if (rs.next() == false)
541                throw new NoSuchEntityException JavaDoc("EntityExc id " + id +
542                                           " not found in database.");
543             int ret = rs.getInt(1);
544
545             if (debug)
546                log.debug("EntityExcBean.get_val() returning " + ret);
547
548             return ret;
549          } finally {
550             rs.close();
551          }
552       } finally {
553          stmt.close();
554       }
555    }
556
557    /**
558     * Write the <code>val</code> property to the database,
559     * using the given connection.
560     */

561    private void set_val(int val, Connection JavaDoc conn)
562       throws SQLException JavaDoc
563    {
564       if (debug)
565          log.debug("EntityExcBean.set_val(" + val + ") entered.");
566
567       PreparedStatement JavaDoc stmt = conn.prepareStatement("update entityexc " +
568                                                      "set val=? " +
569                                                      "where id=?");
570       try {
571          stmt.setInt(1, val);
572          stmt.setInt(2, id);
573          stmt.executeUpdate();
574       } finally {
575          stmt.close();
576       }
577    }
578
579    //
580
// Business methods.
581
//
582

583    public int getId()
584    {
585       if (debug)
586          log.debug("EntityExcBean.getId() entered.");
587
588       checkDiscarded();
589
590       return id;
591    }
592
593    public int getVal()
594    {
595       if (debug)
596          log.debug("EntityExcBean.getVal() entered.");
597
598       checkDiscarded();
599
600       try {
601          Connection JavaDoc conn = getDataSource().getConnection();
602
603          try {
604             return get_val(conn);
605          } finally {
606             conn.close();
607          }
608       } catch (SQLException JavaDoc ex) {
609          wasDiscarded = true;
610          throw new EJBException JavaDoc(ex);
611       }
612    }
613
614    public void incrementVal()
615    {
616       if (debug)
617          log.debug("EntityExcBean.incrementVal(void) entered.");
618
619       checkDiscarded();
620
621       try {
622          Connection JavaDoc conn = getDataSource().getConnection();
623
624          try {
625             set_val(get_val(conn) + 1, conn);
626          } finally {
627             conn.close();
628          }
629       } catch (SQLException JavaDoc ex) {
630          wasDiscarded = true;
631          throw new EJBException JavaDoc(ex);
632       }
633    }
634
635    public void incrementVal(int flags)
636       throws MyAppException
637    {
638       if (debug)
639          log.debug("EntityExcBean.incrementVal(flags=0x" +
640                             Integer.toHexString(flags) + ") entered.");
641
642       checkDiscarded();
643
644       doFailureOnlyAppExc(false, flags);
645
646       incrementVal();
647
648       doFailureOnlyAppExc(true, flags);
649    }
650
651 }
652
Popular Tags