KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openejb > test > entity > bmp > BasicBmpBean


1 /**
2  * Redistribution and use of this software and associated documentation
3  * ("Software"), with or without modification, are permitted provided
4  * that the following conditions are met:
5  *
6  * 1. Redistributions of source code must retain copyright
7  * statements and notices. Redistributions must also contain a
8  * copy of this document.
9  *
10  * 2. Redistributions in binary form must reproduce the
11  * above copyright notice, this list of conditions and the
12  * following disclaimer in the documentation and/or other
13  * materials provided with the distribution.
14  *
15  * 3. The name "Exolab" must not be used to endorse or promote
16  * products derived from this Software without prior written
17  * permission of Exoffice Technologies. For written permission,
18  * please contact info@exolab.org.
19  *
20  * 4. Products derived from this Software may not be called "Exolab"
21  * nor may "Exolab" appear in their names without prior written
22  * permission of Exoffice Technologies. Exolab is a registered
23  * trademark of Exoffice Technologies.
24  *
25  * 5. Due credit should be given to the Exolab Project
26  * (http://www.exolab.org/).
27  *
28  * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
30  * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
31  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
32  * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
33  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
34  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
37  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
39  * OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  * Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved.
42  *
43  * $Id: BasicBmpBean.java 1096 2004-03-26 21:41:16Z dblevins $
44  */

45 package org.openejb.test.entity.bmp;
46
47 import java.rmi.RemoteException JavaDoc;
48 import java.sql.Connection JavaDoc;
49 import java.sql.PreparedStatement JavaDoc;
50 import java.sql.ResultSet JavaDoc;
51 import java.util.Hashtable JavaDoc;
52 import java.util.Properties JavaDoc;
53 import java.util.StringTokenizer JavaDoc;
54
55 import javax.ejb.EJBException JavaDoc;
56 import javax.ejb.EntityContext JavaDoc;
57 import javax.ejb.FinderException JavaDoc;
58 import javax.ejb.RemoveException JavaDoc;
59 import javax.naming.InitialContext JavaDoc;
60 import javax.sql.DataSource JavaDoc;
61
62 import org.openejb.test.ApplicationException;
63 import org.openejb.test.object.OperationsPolicy;
64
65 /**
66  *
67  * @author <a HREF="mailto:david.blevins@visi.com">David Blevins</a>
68  * @author <a HREF="mailto:Richard@Monson-Haefel.com">Richard Monson-Haefel</a>
69  */

70 public class BasicBmpBean implements javax.ejb.EntityBean JavaDoc {
71
72     //public static int keys = 100;
73
public int primaryKey;
74     public String JavaDoc firstName;
75     public String JavaDoc lastName;
76     public EntityContext JavaDoc ejbContext;
77     public Hashtable JavaDoc allowedOperationsTable = new Hashtable JavaDoc();
78
79
80     //=============================
81
// Home interface methods
82
//
83

84     /**
85      * Maps to BasicBmpHome.sum
86      *
87      * Adds x and y and returns the result.
88      *
89      * @param one
90      * @param two
91      * @return x + y
92      * @see BasicBmpHome.sum
93      */

94     public int ejbHomeSum(int x, int y) {
95         testAllowedOperations("ejbHome");
96         return x+y;
97     }
98
99
100     /**
101      * Maps to BasicBmpHome.findEmptyCollection
102      *
103      * @param primaryKey
104      * @return
105      * @exception javax.ejb.FinderException
106      * @see BasicBmpHome.sum
107      */

108     public java.util.Collection JavaDoc ejbFindEmptyCollection()
109     throws javax.ejb.FinderException JavaDoc, java.rmi.RemoteException JavaDoc {
110         return new java.util.Vector JavaDoc();
111     }
112
113     /**
114      * Maps to BasicBmpHome.findEmptyEnumeration()
115      *
116      * @return empty enumeration
117      * @throws javax.ejb.FinderException
118      */

119     public java.util.Enumeration JavaDoc ejbFindEmptyEnumeration()
120     throws javax.ejb.FinderException JavaDoc
121     {
122         return (new java.util.Vector JavaDoc()).elements();
123     }
124     
125     /**
126      * Maps to BasicBmpHome.findByPrimaryKey
127      *
128      * @param primaryKey
129      * @return
130      * @exception javax.ejb.FinderException
131      * @see BasicBmpHome.sum
132      */

133     public Integer JavaDoc ejbFindByPrimaryKey(Integer JavaDoc primaryKey)
134     throws javax.ejb.FinderException JavaDoc{
135         boolean found = false;
136         try {
137             InitialContext JavaDoc jndiContext = new InitialContext JavaDoc( );
138             DataSource JavaDoc ds = (DataSource JavaDoc)jndiContext.lookup("java:comp/env/jdbc/basic/entityDatabase");
139             Connection JavaDoc con = ds.getConnection();
140
141             PreparedStatement JavaDoc stmt = con.prepareStatement("select * from entity where id = ?");
142             stmt.setInt(1, primaryKey.intValue());
143             found = stmt.executeQuery().next();
144             con.close();
145         } catch ( Exception JavaDoc e ) {
146             throw new FinderException JavaDoc("FindByPrimaryKey failed");
147         }
148
149         if ( found ) return primaryKey;
150         else throw new javax.ejb.ObjectNotFoundException JavaDoc();
151     }
152
153     /**
154      * Maps to BasicBmpHome.findByPrimaryKey
155      *
156      * @param primaryKey
157      * @return
158      * @exception javax.ejb.FinderException
159      * @see BasicBmpHome.sum
160      */

161     public java.util.Collection JavaDoc ejbFindByLastName(String JavaDoc lastName)
162     throws javax.ejb.FinderException JavaDoc{
163         java.util.Vector JavaDoc keys = new java.util.Vector JavaDoc();
164         try {
165             InitialContext JavaDoc jndiContext = new InitialContext JavaDoc( );
166             DataSource JavaDoc ds = (DataSource JavaDoc)jndiContext.lookup("java:comp/env/jdbc/basic/entityDatabase");
167             Connection JavaDoc con = ds.getConnection();
168
169             PreparedStatement JavaDoc stmt = con.prepareStatement("SELECT id FROM entity WHERE last_name = ?");
170             stmt.setString(1, lastName);
171
172             ResultSet JavaDoc set = stmt.executeQuery();
173
174             while ( set.next() ) keys.add( new Integer JavaDoc(set.getInt("id")) );
175             con.close();
176         } catch ( Exception JavaDoc e ) {
177             throw new FinderException JavaDoc("FindByPrimaryKey failed");
178         }
179
180         if ( keys.size() > 0 ) return keys;
181         else throw new javax.ejb.ObjectNotFoundException JavaDoc();
182     }
183     /**
184      * Maps to BasicBmpHome.create
185      *
186      * @param name
187      * @return
188      * @exception javax.ejb.CreateException
189      * @see BasicBmpHome.create
190      */

191     public Integer JavaDoc ejbCreate(String JavaDoc name)
192     throws javax.ejb.CreateException JavaDoc{
193         try {
194             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(name, " ");
195             firstName = st.nextToken();
196             lastName = st.nextToken();
197
198             InitialContext JavaDoc jndiContext = new InitialContext JavaDoc( );
199
200             DataSource JavaDoc ds = (DataSource JavaDoc)jndiContext.lookup("java:comp/env/jdbc/basic/entityDatabase");
201
202             Connection JavaDoc con = ds.getConnection();
203
204             // Support for Oracle because Oracle doesn't do auto increment
205
// PreparedStatement stmt = con.prepareStatement("insert into entity (id, first_name, last_name) values (?,?,?)");
206
// stmt.setInt(1, keys++);
207
// stmt.setString(2, firstName);
208
// stmt.setString(3, lastName);
209
// stmt.executeUpdate();
210
PreparedStatement JavaDoc stmt = con.prepareStatement("insert into entity (first_name, last_name) values (?,?)");
211             stmt.setString(1, firstName);
212             stmt.setString(2, lastName);
213             stmt.executeUpdate();
214
215             stmt = con.prepareStatement("select id from entity where first_name = ? AND last_name = ?");
216             stmt.setString(1, firstName);
217             stmt.setString(2, lastName);
218             ResultSet JavaDoc set = stmt.executeQuery();
219             while ( set.next() ) primaryKey = set.getInt("id");
220             con.close();
221
222             return new Integer JavaDoc(primaryKey);
223
224         } catch ( Exception JavaDoc e ) {
225             e.printStackTrace();
226             throw new javax.ejb.CreateException JavaDoc("can't create: "+e.getClass().getName()+" "+e.getMessage());
227         }
228     }
229
230     public void ejbPostCreate(String JavaDoc name)
231     throws javax.ejb.CreateException JavaDoc{
232     }
233
234     //
235
// Home interface methods
236
//=============================
237

238
239     //=============================
240
// Remote interface methods
241
//
242

243     /**
244      * Maps to BasicBmpObject.businessMethod
245      *
246      * @return
247      * @see BasicBmpObject.businessMethod
248      */

249     public String JavaDoc businessMethod(String JavaDoc text) {
250         testAllowedOperations("businessMethod");
251         StringBuffer JavaDoc b = new StringBuffer JavaDoc(text);
252         return b.reverse().toString();
253     }
254
255
256     /**
257      * Throws an ApplicationException when invoked
258      *
259      */

260     public void throwApplicationException() throws ApplicationException{
261         throw new ApplicationException("Testing ability to throw Application Exceptions");
262     }
263     
264     /**
265      * Throws a java.lang.NullPointerException when invoked
266      * This is a system exception and should result in the
267      * destruction of the instance and invalidation of the
268      * remote reference.
269      *
270      */

271     public void throwSystemException_NullPointer() {
272         throw new NullPointerException JavaDoc("Testing ability to throw System Exceptions");
273     }
274     
275
276     /**
277      * Maps to BasicBmpObject.getPermissionsReport
278      *
279      * Returns a report of the bean's
280      * runtime permissions
281      *
282      * @return
283      * @see BasicBmpObject.getPermissionsReport
284      */

285     public Properties JavaDoc getPermissionsReport() {
286         /* TO DO: */
287         return null;
288     }
289
290     /**
291      * Maps to BasicBmpObject.getAllowedOperationsReport
292      *
293      * Returns a report of the allowed opperations
294      * for one of the bean's methods.
295      *
296      * @param methodName The method for which to get the allowed opperations report
297      * @return
298      * @see BasicBmpObject.getAllowedOperationsReport
299      */

300     public OperationsPolicy getAllowedOperationsReport(String JavaDoc methodName) {
301         return(OperationsPolicy) allowedOperationsTable.get(methodName);
302     }
303
304     //
305
// Remote interface methods
306
//=============================
307

308
309     //================================
310
// EntityBean interface methods
311
//
312

313     /**
314      * A container invokes this method to instruct the
315      * instance to synchronize its state by loading it state from the
316      * underlying database.
317      */

318     public void ejbLoad() throws EJBException JavaDoc,RemoteException JavaDoc {
319         try {
320             InitialContext JavaDoc jndiContext = new InitialContext JavaDoc( );
321             DataSource JavaDoc ds = (DataSource JavaDoc)jndiContext.lookup("java:comp/env/jdbc/basic/entityDatabase");
322             Connection JavaDoc con = ds.getConnection();
323
324             PreparedStatement JavaDoc stmt = con.prepareStatement("select * from entity where id = ?");
325             Integer JavaDoc primaryKey = (Integer JavaDoc)ejbContext.getPrimaryKey();
326             stmt.setInt(1, primaryKey.intValue());
327             ResultSet JavaDoc rs = stmt.executeQuery();
328             while ( rs.next() ) {
329                 lastName = rs.getString("last_name");
330                 firstName = rs.getString("first_name");
331             }
332             con.close();
333
334         } catch ( Exception JavaDoc e ) {
335             e.printStackTrace();
336         }
337     }
338
339     /**
340      * Set the associated entity context. The container invokes this method
341      * on an instance after the instance has been created.
342      */

343     public void setEntityContext(EntityContext JavaDoc ctx) throws EJBException JavaDoc,RemoteException JavaDoc {
344         ejbContext = ctx;
345         testAllowedOperations("setEntityContext");
346     }
347
348     /**
349      * Unset the associated entity context. The container calls this method
350      * before removing the instance.
351      */

352     public void unsetEntityContext() throws EJBException JavaDoc,RemoteException JavaDoc {
353         testAllowedOperations("unsetEntityContext");
354     }
355
356     /**
357      * A container invokes this method to instruct the
358      * instance to synchronize its state by storing it to the underlying
359      * database.
360      */

361     public void ejbStore() throws EJBException JavaDoc,RemoteException JavaDoc {
362         try {
363             InitialContext JavaDoc jndiContext = new InitialContext JavaDoc( );
364             DataSource JavaDoc ds = (DataSource JavaDoc)jndiContext.lookup("java:comp/env/jdbc/basic/entityDatabase");
365             Connection JavaDoc con = ds.getConnection();
366
367             PreparedStatement JavaDoc stmt = con.prepareStatement("update entity set first_name = ?, last_name = ? where id = ?");
368             stmt.setString(1, firstName);
369             stmt.setString(2, lastName);
370             stmt.setInt(3, primaryKey);
371             stmt.execute();
372             con.close();
373         } catch ( Exception JavaDoc e ) {
374             e.printStackTrace();
375         }
376     }
377
378     /**
379      * A container invokes this method before it removes the EJB object
380      * that is currently associated with the instance. This method
381      * is invoked when a client invokes a remove operation on the
382      * enterprise Bean's home interface or the EJB object's remote interface.
383      * This method transitions the instance from the ready state to the pool
384      * of available instances.
385      */

386     public void ejbRemove() throws RemoveException JavaDoc,EJBException JavaDoc,RemoteException JavaDoc {
387         try {
388             InitialContext JavaDoc jndiContext = new InitialContext JavaDoc( );
389             DataSource JavaDoc ds = (DataSource JavaDoc)jndiContext.lookup("java:comp/env/jdbc/basic/entityDatabase");
390             Connection JavaDoc con = ds.getConnection();
391
392             PreparedStatement JavaDoc stmt = con.prepareStatement("delete from entity where id = ?");
393             Integer JavaDoc primaryKey = (Integer JavaDoc)ejbContext.getPrimaryKey();
394             stmt.setInt(1, primaryKey.intValue());
395             stmt.executeUpdate();
396             con.close();
397
398         } catch ( Exception JavaDoc e ) {
399             e.printStackTrace();
400             throw new javax.ejb.EJBException JavaDoc(e);
401         }
402     }
403
404     /**
405      * A container invokes this method when the instance
406      * is taken out of the pool of available instances to become associated
407      * with a specific EJB object. This method transitions the instance to
408      * the ready state.
409      */

410     public void ejbActivate() throws EJBException JavaDoc,RemoteException JavaDoc {
411         testAllowedOperations("ejbActivate");
412     }
413
414     /**
415      * A container invokes this method on an instance before the instance
416      * becomes disassociated with a specific EJB object. After this method
417      * completes, the container will place the instance into the pool of
418      * available instances.
419      */

420     public void ejbPassivate() throws EJBException JavaDoc,RemoteException JavaDoc {
421         testAllowedOperations("ejbPassivate");
422     }
423
424
425     //
426
// EntityBean interface methods
427
//================================
428

429     protected void testAllowedOperations(String JavaDoc methodName) {
430         OperationsPolicy policy = new OperationsPolicy();
431
432         /*[0] Test getEJBHome /////////////////*/
433         try {
434             ejbContext.getEJBHome();
435             policy.allow(policy.Context_getEJBHome);
436         } catch ( IllegalStateException JavaDoc ise ) {
437         }
438
439         /*[1] Test getCallerPrincipal /////////*/
440         try {
441             ejbContext.getCallerPrincipal();
442             policy.allow( policy.Context_getCallerPrincipal );
443         } catch ( IllegalStateException JavaDoc ise ) {
444         }
445
446         /*[2] Test isCallerInRole /////////////*/
447         try {
448             ejbContext.isCallerInRole("ROLE");
449             policy.allow( policy.Context_isCallerInRole );
450         } catch ( IllegalStateException JavaDoc ise ) {
451         }
452
453         /*[3] Test getRollbackOnly ////////////*/
454         try {
455             ejbContext.getRollbackOnly();
456             policy.allow( policy.Context_getRollbackOnly );
457         } catch ( IllegalStateException JavaDoc ise ) {
458         }
459
460         /*[4] Test setRollbackOnly ////////////*/
461         try {
462             ejbContext.setRollbackOnly();
463             policy.allow( policy.Context_setRollbackOnly );
464         } catch ( IllegalStateException JavaDoc ise ) {
465         }
466
467         /*[5] Test getUserTransaction /////////*/
468         try {
469             ejbContext.getUserTransaction();
470             policy.allow( policy.Context_getUserTransaction );
471         } catch ( IllegalStateException JavaDoc ise ) {
472         }
473
474         /*[6] Test getEJBObject ///////////////*/
475         try {
476             ejbContext.getEJBObject();
477             policy.allow( policy.Context_getEJBObject );
478         } catch ( IllegalStateException JavaDoc ise ) {
479         }
480
481         /*[7] Test Context_getPrimaryKey ///////////////
482          *
483          * Can't really do this
484          */

485
486         /*[8] Test JNDI_access_to_java_comp_env ///////////////*/
487         try {
488             InitialContext JavaDoc jndiContext = new InitialContext JavaDoc();
489
490             String JavaDoc actual = (String JavaDoc)jndiContext.lookup("java:comp/env/stateless/references/JNDI_access_to_java_comp_env");
491
492             policy.allow( policy.JNDI_access_to_java_comp_env );
493         } catch ( IllegalStateException JavaDoc ise ) {
494         } catch ( javax.naming.NamingException JavaDoc ne ) {
495         }
496
497         /*[9] Test Resource_manager_access ///////////////*/
498         try {
499             InitialContext JavaDoc jndiContext = new InitialContext JavaDoc( );
500
501             DataSource JavaDoc ds = (DataSource JavaDoc)jndiContext.lookup("java:comp/env/stateless/references/Resource_manager_access");
502
503             policy.allow( policy.Resource_manager_access );
504         } catch ( IllegalStateException JavaDoc ise ) {
505         } catch ( javax.naming.NamingException JavaDoc ne ) {
506         }
507
508         /*[10] Test Enterprise_bean_access ///////////////*/
509         try {
510             InitialContext JavaDoc jndiContext = new InitialContext JavaDoc( );
511
512             Object JavaDoc obj = jndiContext.lookup("java:comp/env/stateless/beanReferences/Enterprise_bean_access");
513
514             policy.allow( policy.Enterprise_bean_access );
515         } catch ( IllegalStateException JavaDoc ise ) {
516         } catch ( javax.naming.NamingException JavaDoc ne ) {
517         }
518
519         allowedOperationsTable.put(methodName, policy);
520     }
521
522 }
523
Popular Tags