001: // OrderEBR.java
002: package org.objectweb.jonas.stests.appli;
003:
004: import java.rmi.RemoteException;
005: import java.sql.Connection;
006: import java.sql.PreparedStatement;
007: import java.sql.ResultSet;
008: import java.sql.SQLException;
009: import java.sql.Statement;
010: import java.util.Enumeration;
011: import java.util.Vector;
012:
013: import javax.ejb.CreateException;
014: import javax.ejb.EJBException;
015: import javax.ejb.EntityBean;
016: import javax.ejb.EntityContext;
017: import javax.ejb.FinderException;
018: import javax.ejb.RemoveException;
019: import javax.naming.Context;
020: import javax.naming.InitialContext;
021: import javax.sql.DataSource;
022:
023: import org.objectweb.jonas.common.Log;
024: import org.objectweb.util.monolog.api.BasicLevel;
025: import org.objectweb.util.monolog.api.Logger;
026:
027: /**
028: *
029: */
030: public class OrderEBR implements EntityBean {
031:
032: static private Logger logger = null;
033:
034: // ------------------------------------------------------------------
035: // State of the bean.
036: //
037: // ------------------------------------------------------------------
038:
039: // Publically accessible member data that will be persisted
040: public String ivWarehouseID;
041: public int ivDistrictID;
042: public Integer ivCustomerID;
043: public float ivOrderID;
044: public int ivNumberOfOrderLines;
045: //A Vector of OrderDetail objects belonging to the Order
046: public Vector ivOrderItems;
047: // private variables
048: private transient boolean isDirty;
049: private transient EntityContext ctx;
050: // (The DataSource can be shared among all instances)
051: protected static DataSource dataSource = null;
052: // table names
053: private static String ordersTable = null;
054: private static String orderlinesTable = null;
055:
056: // ------------------------------------------------------------------
057: // EntityBean implementation
058: // ------------------------------------------------------------------
059:
060: public boolean isModified() {
061: return isDirty;
062: }
063:
064: public void setModified(boolean flag) {
065: isDirty = flag;
066: }
067:
068: public void setEntityContext(EntityContext ctxt) {
069: if (logger == null) {
070: logger = Log.getLogger("org.objectweb.jonas_tests");
071: }
072: logger.log(BasicLevel.DEBUG, "");
073: ctx = ctxt;
074: if (ordersTable == null) {
075: try {
076: initialContext = new InitialContext();
077: ordersTable = (String) initialContext
078: .lookup("java:comp/env/OrderTableName");
079: orderlinesTable = (String) initialContext
080: .lookup("java:comp/env/OrderlineTableName");
081: } catch (Exception e) {
082: logger.log(BasicLevel.ERROR, "cannot lookup env-entry "
083: + e);
084: System.exit(2); // stop all
085: }
086: }
087: }
088:
089: public void unsetEntityContext() {
090: logger.log(BasicLevel.DEBUG, "");
091: ctx = null;
092: }
093:
094: static final String tableName = "orderOrderEBR";
095:
096: public void ejbRemove() throws RemoveException {
097: logger.log(BasicLevel.DEBUG, "");
098: Connection con = null;
099: Statement stmt = null;
100: try {
101: con = getConnection();
102: OrderID pk = (OrderID) ctx.getPrimaryKey();
103:
104: // Delete all the order line records
105: String deleteLineSQL = "delete from " + orderlinesTable
106: + " where " + "olwid = '" + pk.ivWarehouseID
107: + "' " + "and oldid = " + pk.ivDistrictID + " "
108: + "and oloid = " + pk.ivOrderID;
109: stmt = con.createStatement();
110: int lineCount = stmt.executeUpdate(deleteLineSQL);
111: if (lineCount == 0) {
112: throw new RemoveException(
113: "Failed to delete bean from database lineCount == 0");
114: }
115: stmt.close();
116:
117: // Delete the order record
118: String deleteOrderSQL = "delete from " + ordersTable
119: + " where " + "owid = '" + pk.ivWarehouseID + "' "
120: + "and odid = " + pk.ivDistrictID + " "
121: + "and ooid = " + pk.ivOrderID;
122: stmt = con.createStatement();
123: int orderCount = stmt.executeUpdate(deleteOrderSQL);
124: stmt.close();
125: if (orderCount == 0) {
126: throw new RemoveException("Failed to delete"
127: + ivOrderID + ") from database lineCount == 0");
128: }
129:
130: } catch (SQLException sqe) {
131: throw new RemoveException(sqe.getMessage());
132: } finally {
133: try {
134: con.close();
135: } catch (Exception ignore) {
136: }
137: }
138:
139: }
140:
141: public void ejbLoad() {
142: logger.log(BasicLevel.DEBUG, "");
143: //Get the primary key from the context object.
144: OrderID pk = (OrderID) ctx.getPrimaryKey();
145:
146: Connection con = null;
147: Statement stmt = null;
148:
149: try {
150: con = getConnection();
151:
152: // Create a new Vector to hold order lines.
153: // Retrieve all the order lines that match the supplied primary key.
154: // For each order line, create a new OrderDetail object and store it on the Vector.
155: // Replace the existing ivOrderItems with the new Vector
156:
157: Vector newOrderLines = new Vector();
158: String selectLineSQL = "select * from " + orderlinesTable
159: + " where " + "olwid = '" + pk.ivWarehouseID + "' "
160: + "and oldid = " + pk.ivDistrictID + " "
161: + "and oloid = " + pk.ivOrderID;
162: stmt = con.createStatement();
163: ResultSet rsLines = stmt.executeQuery(selectLineSQL);
164: while (rsLines.next()) {
165: Integer itemID = new Integer(rsLines.getInt("OLIID"));
166: float amount = rsLines.getFloat("OLAMNT");
167: int qty = rsLines.getInt("OLQTY");
168: int lineNumber = rsLines.getInt("OLNBR");
169: OrderDetail od = new OrderDetail(itemID, amount, qty);
170: od.setLineNumber(lineNumber);
171: newOrderLines.addElement(od);
172: }
173: rsLines.close();
174: stmt.close();
175:
176: ivOrderItems = newOrderLines;
177: ivNumberOfOrderLines = ivOrderItems.size();
178:
179: // Retrieve the order header information from the orders table and
180: // replace the order instance variables
181: //
182: String selectOrderSQL = "select * from " + ordersTable
183: + " where " + "owid = '" + pk.ivWarehouseID + "' "
184: + "and odid = " + pk.ivDistrictID + " "
185: + "and ooid = " + pk.ivOrderID;
186: stmt = con.createStatement();
187: ResultSet rsOrder = stmt.executeQuery(selectOrderSQL);
188: if (rsOrder.next()) {
189: ivWarehouseID = pk.ivWarehouseID;
190: ivDistrictID = pk.ivDistrictID;
191: ivCustomerID = new Integer(rsOrder.getInt("ocid"));
192: ivOrderID = pk.ivOrderID;
193: } else {
194: throw new EJBException("Order " + pk.ivOrderID
195: + " not found.");
196: }
197: rsOrder.close();
198: stmt.close();
199: setModified(false);
200: } catch (SQLException sqe) {
201: throw new EJBException(sqe.getMessage());
202: } finally {
203: try {
204: con.close();
205: } catch (Exception ignore) {
206: }
207: }
208: }
209:
210: public void ejbStore() {
211: logger.log(BasicLevel.DEBUG, "");
212: if (!isModified())
213: return;
214: Connection con = null;
215: PreparedStatement ps = null;
216: Statement stmt = null;
217: try {
218: con = getConnection();
219:
220: // Create an sql prepared statement that will be used for each order line.
221: // The modifiable values are item id (oliid), qty (olqty), and price (olamnt).
222: ps = con
223: .prepareStatement("update ordlin set oliid = ?, olqty = ?, olamnt = ? "
224: + "where oloid = "
225: + ivOrderID
226: + " "
227: + "and oldid = "
228: + ivDistrictID
229: + " "
230: + "and olwid = '"
231: + ivWarehouseID
232: + "' "
233: + "and olnbr = ?");
234:
235: // Iterate through each order line and update the record into the database
236: Enumeration enumer = ivOrderItems.elements();
237: while (enumer.hasMoreElements()) {
238: OrderDetail od = (OrderDetail) enumer.nextElement();
239: ps.setInt(1, od.getItemID().intValue());
240: ps.setInt(2, od.getItemQty());
241: ps.setFloat(3, od.getItemAmount());
242: ps.setInt(4, od.getLineNumber());
243: int lineCount = ps.executeUpdate();
244: if (lineCount == 0) {
245: throw new EJBException("ejbStore: OrderBean ("
246: + ivOrderID + ") not updated");
247: }
248: }
249:
250: // Update the order table record
251: // The modifiable values are customer id (ocid) and number of order lines (olines).
252: String updateSQL = "update " + ordersTable + " set "
253: + "ocid = '" + ivCustomerID + "', " + "olines = "
254: + ivNumberOfOrderLines + " " + "where owid = '"
255: + ivWarehouseID + "' " + "and odid = "
256: + ivDistrictID + " " + "and ooid = " + ivOrderID;
257:
258: stmt = con.createStatement();
259: int orderCount = stmt.executeUpdate(updateSQL);
260: if (orderCount == 0) {
261: throw new EJBException("ejbStore: OrderBean ("
262: + ivOrderID + ") not updated");
263: }
264:
265: setModified(false);
266:
267: } catch (SQLException sqe) {
268: throw new EJBException(sqe.getMessage());
269: } finally {
270: try {
271: stmt.close();
272: ps.close();
273: con.close();
274: } catch (Exception ignore) {
275: }
276: }
277:
278: }
279:
280: public void ejbPassivate() {
281: logger.log(BasicLevel.DEBUG, "");
282: }
283:
284: public void ejbActivate() {
285: logger.log(BasicLevel.DEBUG, "");
286: }
287:
288: public void ejbPostCreate(String warehouseID, int districtID,
289: Integer customerID, float orderID, Vector orderItems) {
290: logger.log(BasicLevel.DEBUG, "");
291: }
292:
293: /**
294: * This method is called when a client calls the OrderHome.create(). It creates
295: * records in the database for the line items and the order header information.
296: * @param warehouseID String Warehouse ID
297: * @param districtID int District ID
298: * @param customerID Integer Customer ID
299: * @param orderID float Order ID - NOTE: must be passed in as parameter, it is not created by the bean
300: * @param orderItems Vector of OrderDetail objects. Each OrderDetail object represents one line item on the order. The bean determines the order line number.
301: * @exception javax.ejb.CreateException
302: * @exception javax.ejb.RemoteException
303: */
304: /* Use separate conneciton objects for ordlin and orders */
305: public OrderID ejbCreate(String warehouseID, int districtID,
306: Integer customerID, float orderID, Vector orderItems)
307: throws CreateException, RemoteException {
308: logger.log(BasicLevel.DEBUG, "");
309: ivWarehouseID = warehouseID;
310: ivDistrictID = districtID;
311: ivCustomerID = customerID;
312: ivOrderID = orderID;
313: ivNumberOfOrderLines = orderItems.size();
314: ivOrderItems = orderItems;
315: // Use JDBC to store the Order to the database
316: Connection con = null;
317: try {
318: con = getConnection();
319: // Iterate through each order line and insert a record into the database
320: int orderLineNumber = 1;
321: Enumeration enumer = ivOrderItems.elements();
322: while (enumer.hasMoreElements()) {
323: OrderDetail od = (OrderDetail) enumer.nextElement();
324: String orderlineSQL = "insert into "
325: + orderlinesTable
326: + " (OLOID, OLDID, OLWID, OLNBR, OLIID, OLQTY, OLAMNT) "
327: + "values (" + ivOrderID + ", " + ivDistrictID
328: + ", '" + ivWarehouseID + "'" + ", "
329: + orderLineNumber + ", '" + od.getItemID()
330: + "'" + ", " + od.getItemQty() + ", "
331: + od.getItemAmount() + ")";
332: Statement stmtLine = con.createStatement();
333: logger.log(BasicLevel.DEBUG, "orderlineSQL= "
334: + orderlineSQL);
335: int lineCount = stmtLine.executeUpdate(orderlineSQL);
336: if (lineCount == 0) {
337: logger.log(BasicLevel.DEBUG, "lineCount == 0");
338: throw new CreateException(
339: "Unable to create order line item: "
340: + orderLineNumber);
341: }
342: stmtLine.close();
343: od.setLineNumber(orderLineNumber); //Store the line number in the order detail object.
344: orderLineNumber++;
345: }
346:
347: // Insert a record into the order table
348: String insertSQL = "insert into " + ordersTable
349: + "(OWID, ODID, OCID, OOID, OLINES) values (" + "'"
350: + ivWarehouseID + "', " + ivDistrictID + ", " + "'"
351: + ivCustomerID + "', " + ivOrderID + ", "
352: + ivNumberOfOrderLines + ")";
353: Statement stmtOrder = con.createStatement();
354: logger.log(BasicLevel.DEBUG, "insertSQL= " + insertSQL);
355: int orderCount = stmtOrder.executeUpdate(insertSQL);
356: if (orderCount == 0) {
357: throw new CreateException("Unable to create order");
358: }
359: stmtOrder.close();
360:
361: // Create the primary key
362: OrderID oID = new OrderID(ivWarehouseID, ivDistrictID,
363: ivOrderID);
364:
365: return oID;
366:
367: } catch (CreateException ce) {
368: System.out.println("CreateException thrown: "
369: + ce.getMessage());
370: throw ce;
371: } catch (SQLException sqe) {
372: System.out.println("SQLException thrown: "
373: + sqe.getMessage());
374: throw new CreateException(sqe.getMessage());
375: } finally {
376: try {
377: con.close();
378: } catch (Exception ignore) {
379: }
380: }
381:
382: }
383:
384: public OrderID ejbFindByPrimaryKey(OrderID pk)
385: throws FinderException {
386: logger.log(BasicLevel.DEBUG, "");
387: if (pk == null) {
388: throw new FinderException(
389: "ejbFindByPrimaryKey: null primary key");
390: }
391:
392: Connection con = null;
393: Statement stmt = null;
394:
395: try {
396: con = getConnection();
397: // Find the order in the orders table
398: String selectOrderSQL = "select * from " + ordersTable
399: + " where " + "owid = '" + pk.ivWarehouseID + "' "
400: + "and odid = " + pk.ivDistrictID + " "
401: + "and ooid = " + pk.ivOrderID;
402: stmt = con.createStatement();
403: ResultSet rsOrder = stmt.executeQuery(selectOrderSQL);
404: if (rsOrder.next()) {
405: //Order found, don't throw exception
406: } else {
407: //Order not fount, throw exception
408: throw new FinderException("Order " + pk.ivOrderID
409: + " not found.");
410: }
411: rsOrder.close();
412: stmt.close();
413:
414: } catch (SQLException sqe) {
415: //Unable to find the order because of an SQL error.
416: throw new FinderException(sqe.getMessage());
417: } finally {
418: try {
419: con.close();
420: } catch (Exception ignore) {
421: }
422: }
423: return pk;
424:
425: }
426:
427: /**
428: * Finds an order given the warehouse, district and order IDs as Strings.
429: * The method constructs an OrderID from the three parameters and calls
430: * ejbFindByPrimaryKey().
431: *
432: * @param wID String Warehouse ID
433: * @param dID String District ID
434: * @param oID String Order ID
435: *
436: * @exception java.rmi.RemoteException
437: * @exception javax.ejb.FinderException
438: * thrown if the EJBean cannot be found.
439: */
440: public OrderID ejbFindByID(String wID, String dID, String oID)
441: throws FinderException, RemoteException {
442:
443: OrderID pk = new OrderID(wID, dID, oID);
444: return ejbFindByPrimaryKey(pk);
445:
446: }
447:
448: private Connection getConnection() throws SQLException {
449: if (dataSource == null) {
450: // Finds DataSource from JNDI
451: try {
452: initialContext = new InitialContext();
453: dataSource = (DataSource) initialContext
454: .lookup("java:comp/env/jdbc/Order");
455: } catch (Exception e) {
456: logger.log(BasicLevel.ERROR, "Pb with naming context");
457: throw new javax.ejb.EJBException(
458: "Pb with naming context ");
459: }
460: }
461: return dataSource.getConnection();
462: }
463:
464: private Context initialContext = null;
465:
466: // ------------------------------------------------------------------
467: // Order implementation
468: // ------------------------------------------------------------------
469:
470: // *********************************************************************** //
471: // Implementation of business methods defined in Order interface
472: // *********************************************************************** //
473:
474: public Integer getCustomerID() throws RemoteException {
475: return ivCustomerID;
476: }
477:
478: public int getOrderLineCount() throws RemoteException {
479: return ivNumberOfOrderLines;
480: }
481:
482: public Vector getOrderItems() throws RemoteException {
483: return ivOrderItems;
484: }
485:
486: }
|