001: /**
002: * Licensed to the Apache Software Foundation (ASF) under one or more
003: * contributor license agreements. See the NOTICE file distributed with
004: * this work for additional information regarding copyright ownership.
005: * The ASF licenses this file to You under the Apache License, Version 2.0
006: * (the "License"); you may not use this file except in compliance with
007: * the License. You may obtain a copy of the License at
008: *
009: * http://www.apache.org/licenses/LICENSE-2.0
010: *
011: * Unless required by applicable law or agreed to in writing, software
012: * distributed under the License is distributed on an "AS IS" BASIS,
013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014: * See the License for the specific language governing permissions and
015: * limitations under the License.
016: */package org.apache.openejb.test.entity.bmp;
017:
018: import java.rmi.RemoteException;
019: import java.rmi.NoSuchObjectException;
020: import java.sql.Connection;
021: import java.sql.PreparedStatement;
022: import java.sql.ResultSet;
023: import java.sql.SQLException;
024: import java.util.Hashtable;
025: import java.util.Properties;
026: import java.util.StringTokenizer;
027:
028: import javax.ejb.EJBException;
029: import javax.ejb.EntityContext;
030: import javax.ejb.FinderException;
031: import javax.ejb.RemoveException;
032: import javax.ejb.NoSuchEntityException;
033: import javax.naming.InitialContext;
034: import javax.naming.NamingException;
035: import javax.sql.DataSource;
036:
037: import org.apache.openejb.test.ApplicationException;
038: import org.apache.openejb.test.object.OperationsPolicy;
039:
040: /**
041: *
042: * @author <a href="mailto:david.blevins@visi.com">David Blevins</a>
043: * @author <a href="mailto:Richard@Monson-Haefel.com">Richard Monson-Haefel</a>
044: */
045: public class BasicBmpBean implements javax.ejb.EntityBean {
046:
047: //public static int keys = 100;
048: public int primaryKey;
049: public String firstName;
050: public String lastName;
051: public EntityContext ejbContext;
052: public Hashtable allowedOperationsTable = new Hashtable();
053:
054: //=============================
055: // Home interface methods
056: //
057:
058: /**
059: * Maps to BasicBmpHome.sum
060: *
061: * Adds x and y and returns the result.
062: *
063: * @param x
064: * @param y
065: * @return x + y
066: * @see BasicBmpHome#sum
067: */
068: public int ejbHomeSum(int x, int y) {
069: testAllowedOperations("ejbHome");
070: return x + y;
071: }
072:
073: /**
074: * Maps to BasicBmpHome.findEmptyCollection
075: *
076: * @return
077: * @exception javax.ejb.FinderException
078: * @see BasicBmpHome#sum
079: */
080: public java.util.Collection ejbFindEmptyCollection()
081: throws javax.ejb.FinderException, java.rmi.RemoteException {
082: return new java.util.Vector();
083: }
084:
085: /**
086: * Maps to BasicBmpHome.findEmptyEnumeration()
087: *
088: * @return empty enumeration
089: * @throws javax.ejb.FinderException
090: */
091: public java.util.Enumeration ejbFindEmptyEnumeration()
092: throws javax.ejb.FinderException {
093: return (new java.util.Vector()).elements();
094: }
095:
096: /**
097: * Maps to BasicBmpHome.findByPrimaryKey
098: *
099: * @param primaryKey
100: * @return
101: * @exception javax.ejb.FinderException
102: * @see BasicBmpHome#sum
103: */
104: public Integer ejbFindByPrimaryKey(Integer primaryKey)
105: throws javax.ejb.FinderException {
106: boolean found = false;
107: try {
108: InitialContext jndiContext = new InitialContext();
109: DataSource ds = (DataSource) jndiContext
110: .lookup("java:comp/env/jdbc/basic/entityDatabase");
111: Connection con = ds.getConnection();
112:
113: try {
114: PreparedStatement stmt = con
115: .prepareStatement("select * from entity where id = ?");
116: try {
117: stmt.setInt(1, primaryKey.intValue());
118: found = stmt.executeQuery().next();
119: } finally {
120: stmt.close();
121: }
122: } finally {
123: con.close();
124: }
125: } catch (Exception e) {
126: throw new FinderException("FindByPrimaryKey failed");
127: }
128:
129: if (found)
130: return primaryKey;
131: else
132: throw new javax.ejb.ObjectNotFoundException();
133: }
134:
135: /**
136: * Maps to BasicBmpHome.findByPrimaryKey
137: *
138: * @param lastName
139: * @return
140: * @exception javax.ejb.FinderException
141: * @see BasicBmpHome#sum
142: */
143: public java.util.Collection ejbFindByLastName(String lastName)
144: throws javax.ejb.FinderException {
145: java.util.Vector keys = new java.util.Vector();
146: try {
147: InitialContext jndiContext = new InitialContext();
148: DataSource ds = (DataSource) jndiContext
149: .lookup("java:comp/env/jdbc/basic/entityDatabase");
150: Connection con = ds.getConnection();
151:
152: try {
153: PreparedStatement stmt = con
154: .prepareStatement("SELECT id FROM entity WHERE last_name = ?");
155: try {
156: stmt.setString(1, lastName);
157: ResultSet set = stmt.executeQuery();
158: while (set.next())
159: keys.add(new Integer(set.getInt("id")));
160: } finally {
161: stmt.close();
162: }
163: } finally {
164: con.close();
165: }
166: } catch (Exception e) {
167: throw new FinderException("FindByPrimaryKey failed");
168: }
169:
170: if (keys.size() > 0)
171: return keys;
172: else
173: throw new javax.ejb.ObjectNotFoundException();
174: }
175:
176: /**
177: * Maps to BasicBmpHome.create
178: *
179: * @param name
180: * @return
181: * @exception javax.ejb.CreateException
182: * @see BasicBmpHome#createObject
183: */
184: public Integer ejbCreateObject(String name)
185: throws javax.ejb.CreateException {
186: try {
187: StringTokenizer st = new StringTokenizer(name, " ");
188: firstName = st.nextToken();
189: lastName = st.nextToken();
190:
191: InitialContext jndiContext = new InitialContext();
192:
193: DataSource ds = (DataSource) jndiContext
194: .lookup("java:comp/env/jdbc/basic/entityDatabase");
195:
196: Connection con = ds.getConnection();
197:
198: try {
199: // Support for Oracle because Oracle doesn't do auto increment
200: // PreparedStatement stmt = con.prepareStatement("insert into entity (id, first_name, last_name) values (?,?,?)");
201: // stmt.setInt(1, keys++);
202: // stmt.setString(2, firstName);
203: // stmt.setString(3, lastName);
204: // stmt.executeUpdate();
205: PreparedStatement stmt = con
206: .prepareStatement("insert into entity (first_name, last_name) values (?,?)");
207: try {
208: stmt.setString(1, firstName);
209: stmt.setString(2, lastName);
210: stmt.executeUpdate();
211: } finally {
212: stmt.close();
213: }
214:
215: stmt = con
216: .prepareStatement("select id from entity where first_name = ? AND last_name = ?");
217: try {
218: stmt.setString(1, firstName);
219: stmt.setString(2, lastName);
220: ResultSet set = stmt.executeQuery();
221: while (set.next())
222: primaryKey = set.getInt("id");
223: } finally {
224: stmt.close();
225: }
226: } finally {
227: con.close();
228: }
229:
230: return new Integer(primaryKey);
231:
232: } catch (Exception e) {
233: e.printStackTrace();
234: throw new javax.ejb.CreateException("can't create: "
235: + e.getClass().getName() + " " + e.getMessage());
236: }
237: }
238:
239: public void ejbPostCreateObject(String name)
240: throws javax.ejb.CreateException {
241: }
242:
243: //
244: // Home interface methods
245: //=============================
246:
247: //=============================
248: // Remote interface methods
249: //
250:
251: /**
252: * Maps to BasicBmpObject.businessMethod
253: *
254: * @return
255: * @see BasicBmpObject#businessMethod
256: */
257: public String businessMethod(String text) {
258: testAllowedOperations("businessMethod");
259: StringBuffer b = new StringBuffer(text);
260: return b.reverse().toString();
261: }
262:
263: /**
264: * Throws an ApplicationException when invoked
265: *
266: */
267: public void throwApplicationException() throws ApplicationException {
268: throw new ApplicationException(
269: "Testing ability to throw Application Exceptions");
270: }
271:
272: /**
273: * Throws a java.lang.NullPointerException when invoked
274: * This is a system exception and should result in the
275: * destruction of the instance and invalidation of the
276: * remote reference.
277: *
278: */
279: public void throwSystemException_NullPointer() {
280: throw new NullPointerException(
281: "Testing ability to throw System Exceptions");
282: }
283:
284: /**
285: * Maps to BasicBmpObject.getPermissionsReport
286: *
287: * Returns a report of the bean's
288: * runtime permissions
289: *
290: * @return
291: * @see BasicBmpObject#getPermissionsReport
292: */
293: public Properties getPermissionsReport() {
294: /* TO DO: */
295: return null;
296: }
297:
298: /**
299: * Maps to BasicBmpObject.getAllowedOperationsReport
300: *
301: * Returns a report of the allowed opperations
302: * for one of the bean's methods.
303: *
304: * @param methodName The method for which to get the allowed opperations report
305: * @return
306: * @see BasicBmpObject#getAllowedOperationsReport
307: */
308: public OperationsPolicy getAllowedOperationsReport(String methodName) {
309: return (OperationsPolicy) allowedOperationsTable
310: .get(methodName);
311: }
312:
313: //
314: // Remote interface methods
315: //=============================
316:
317: //================================
318: // EntityBean interface methods
319: //
320:
321: /**
322: * A container invokes this method to instruct the
323: * instance to synchronize its state by loading it state from the
324: * underlying database.
325: */
326: public void ejbLoad() throws EJBException, RemoteException {
327:
328: try {
329: InitialContext jndiContext = new InitialContext();
330: DataSource ds = (DataSource) jndiContext
331: .lookup("java:comp/env/jdbc/basic/entityDatabase");
332: Connection con = ds.getConnection();
333:
334: try {
335: PreparedStatement stmt = con
336: .prepareStatement("select * from entity where id = ?");
337: try {
338: stmt.setInt(1, primaryKey);
339: ResultSet rs = stmt.executeQuery();
340: if (!rs.next()) {
341: throw new NoSuchEntityException("" + primaryKey);
342: }
343: lastName = rs.getString("last_name");
344: firstName = rs.getString("first_name");
345: if (rs.next()) {
346: throw new EJBException(
347: "Found more than one entity with id "
348: + primaryKey);
349: }
350: } finally {
351: stmt.close();
352: }
353: } finally {
354: con.close();
355: }
356: } catch (NamingException e) {
357: throw new EJBException(e);
358: } catch (SQLException e) {
359: throw new EJBException(e);
360: }
361: }
362:
363: /**
364: * Set the associated entity context. The container invokes this method
365: * on an instance after the instance has been created.
366: */
367: public void setEntityContext(EntityContext ctx)
368: throws EJBException, RemoteException {
369: ejbContext = ctx;
370: testAllowedOperations("setEntityContext");
371: }
372:
373: /**
374: * Unset the associated entity context. The container calls this method
375: * before removing the instance.
376: */
377: public void unsetEntityContext() throws EJBException,
378: RemoteException {
379: testAllowedOperations("unsetEntityContext");
380: }
381:
382: /**
383: * A container invokes this method to instruct the
384: * instance to synchronize its state by storing it to the underlying
385: * database.
386: */
387: public void ejbStore() throws EJBException, RemoteException {
388: try {
389: InitialContext jndiContext = new InitialContext();
390: DataSource ds = (DataSource) jndiContext
391: .lookup("java:comp/env/jdbc/basic/entityDatabase");
392: Connection con = ds.getConnection();
393:
394: try {
395: PreparedStatement stmt = con
396: .prepareStatement("update entity set first_name = ?, last_name = ? where id = ?");
397: try {
398: stmt.setString(1, firstName);
399: stmt.setString(2, lastName);
400: stmt.setInt(3, primaryKey);
401: stmt.execute();
402: } finally {
403: stmt.close();
404: }
405: } finally {
406: con.close();
407: }
408: } catch (Exception e) {
409: e.printStackTrace();
410: }
411: }
412:
413: /**
414: * A container invokes this method before it removes the EJB object
415: * that is currently associated with the instance. This method
416: * is invoked when a client invokes a remove operation on the
417: * enterprise Bean's home interface or the EJB object's remote interface.
418: * This method transitions the instance from the ready state to the pool
419: * of available instances.
420: */
421: public void ejbRemove() throws RemoveException, EJBException,
422: RemoteException {
423: try {
424: InitialContext jndiContext = new InitialContext();
425: DataSource ds = (DataSource) jndiContext
426: .lookup("java:comp/env/jdbc/basic/entityDatabase");
427: Connection con = ds.getConnection();
428:
429: try {
430: PreparedStatement stmt = con
431: .prepareStatement("delete from entity where id = ?");
432: try {
433: stmt.setInt(1, primaryKey);
434: stmt.executeUpdate();
435: } finally {
436: stmt.close();
437: }
438: } finally {
439: con.close();
440: }
441:
442: } catch (Exception e) {
443: e.printStackTrace();
444: throw new javax.ejb.EJBException(e);
445: }
446: }
447:
448: /**
449: * A container invokes this method when the instance
450: * is taken out of the pool of available instances to become associated
451: * with a specific EJB object. This method transitions the instance to
452: * the ready state.
453: */
454: public void ejbActivate() throws EJBException, RemoteException {
455: primaryKey = (Integer) ejbContext.getPrimaryKey();
456: testAllowedOperations("ejbActivate");
457: }
458:
459: /**
460: * A container invokes this method on an instance before the instance
461: * becomes disassociated with a specific EJB object. After this method
462: * completes, the container will place the instance into the pool of
463: * available instances.
464: */
465: public void ejbPassivate() throws EJBException, RemoteException {
466: testAllowedOperations("ejbPassivate");
467: primaryKey = -1;
468: }
469:
470: //
471: // EntityBean interface methods
472: //================================
473:
474: protected void testAllowedOperations(String methodName) {
475: OperationsPolicy policy = new OperationsPolicy();
476:
477: /*[0] Test getEJBHome /////////////////*/
478: try {
479: ejbContext.getEJBHome();
480: policy.allow(policy.Context_getEJBHome);
481: } catch (IllegalStateException ise) {
482: }
483:
484: /*[1] Test getCallerPrincipal /////////*/
485: try {
486: ejbContext.getCallerPrincipal();
487: policy.allow(policy.Context_getCallerPrincipal);
488: } catch (IllegalStateException ise) {
489: }
490:
491: /*[2] Test isCallerInRole /////////////*/
492: try {
493: ejbContext.isCallerInRole("TheMan");
494: policy.allow(policy.Context_isCallerInRole);
495: } catch (IllegalStateException ise) {
496: }
497:
498: /*[3] Test getRollbackOnly ////////////*/
499: try {
500: ejbContext.getRollbackOnly();
501: policy.allow(policy.Context_getRollbackOnly);
502: } catch (IllegalStateException ise) {
503: }
504:
505: /*[4] Test setRollbackOnly ////////////*/
506: try {
507: ejbContext.setRollbackOnly();
508: policy.allow(policy.Context_setRollbackOnly);
509: } catch (IllegalStateException ise) {
510: }
511:
512: /*[5] Test getUserTransaction /////////*/
513: try {
514: ejbContext.getUserTransaction();
515: policy.allow(policy.Context_getUserTransaction);
516: } catch (IllegalStateException ise) {
517: }
518:
519: /*[6] Test getEJBObject ///////////////*/
520: try {
521: ejbContext.getEJBObject();
522: policy.allow(policy.Context_getEJBObject);
523: } catch (IllegalStateException ise) {
524: }
525:
526: /*[7] Test Context_getPrimaryKey ///////////////
527: *
528: * Can't really do this
529: */
530:
531: /*[8] Test JNDI_access_to_java_comp_env ///////////////*/
532: try {
533: InitialContext jndiContext = new InitialContext();
534:
535: String actual = (String) jndiContext
536: .lookup("java:comp/env/stateless/references/JNDI_access_to_java_comp_env");
537:
538: policy.allow(policy.JNDI_access_to_java_comp_env);
539: } catch (IllegalStateException ise) {
540: } catch (javax.naming.NamingException ne) {
541: }
542:
543: allowedOperationsTable.put(methodName, policy);
544: }
545:
546: }
|