KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > stests > appli > OrderEBR


1 // OrderEBR.java
2
package org.objectweb.jonas.stests.appli;
3
4 import java.rmi.RemoteException;
5 import java.sql.Connection;
6 import java.sql.PreparedStatement;
7 import java.sql.ResultSet;
8 import java.sql.SQLException;
9 import java.sql.Statement;
10 import java.util.Enumeration;
11 import java.util.Vector;
12
13 import javax.ejb.CreateException;
14 import javax.ejb.EJBException;
15 import javax.ejb.EntityBean;
16 import javax.ejb.EntityContext;
17 import javax.ejb.FinderException;
18 import javax.ejb.RemoveException;
19 import javax.naming.Context;
20 import javax.naming.InitialContext;
21 import javax.sql.DataSource;
22
23 import org.objectweb.jonas.common.Log;
24 import org.objectweb.util.monolog.api.BasicLevel;
25 import org.objectweb.util.monolog.api.Logger;
26
27 /**
28  *
29  */

30 public class OrderEBR implements EntityBean {
31
32     static private Logger logger = null;
33  
34     // ------------------------------------------------------------------
35
// State of the bean.
36
//
37
// ------------------------------------------------------------------
38

39     // Publically accessible member data that will be persisted
40
public String ivWarehouseID;
41     public int ivDistrictID;
42     public Integer ivCustomerID;
43     public float ivOrderID;
44     public int ivNumberOfOrderLines;
45     //A Vector of OrderDetail objects belonging to the Order
46
public Vector ivOrderItems;
47     // private variables
48
private transient boolean isDirty;
49     private transient EntityContext ctx;
50     // (The DataSource can be shared among all instances)
51
protected static DataSource dataSource = null;
52     // table names
53
private static String ordersTable = null;
54     private static String orderlinesTable = null;
55     // ------------------------------------------------------------------
56
// EntityBean implementation
57
// ------------------------------------------------------------------
58

59     public boolean isModified() {
60     return isDirty;
61     }
62
63     public void setModified(boolean flag) {
64     isDirty = flag;
65     }
66
67     public void setEntityContext(EntityContext ctxt) {
68         if (logger == null) {
69             logger = Log.getLogger("org.objectweb.jonas_tests");
70         }
71         logger.log(BasicLevel.DEBUG, "");
72         ctx = ctxt;
73         if ( ordersTable == null) {
74             try {
75                 initialContext = new InitialContext();
76                 ordersTable = (String) initialContext.lookup("java:comp/env/OrderTableName");
77                 orderlinesTable = (String) initialContext.lookup("java:comp/env/OrderlineTableName");
78             } catch (Exception e) {
79                 logger.log(BasicLevel.ERROR, "cannot lookup env-entry "+e);
80                 System.exit(2); // stop all
81
}
82         }
83     }
84
85     public void unsetEntityContext() {
86         logger.log(BasicLevel.DEBUG, "");
87         ctx = null;
88     }
89
90     static final String tableName = "orderOrderEBR";
91     
92
93     public void ejbRemove() throws RemoveException {
94         logger.log(BasicLevel.DEBUG, "");
95         Connection con = null;
96         Statement stmt = null;
97         try {
98             con = getConnection();
99             OrderID pk = (OrderID) ctx.getPrimaryKey();
100         
101             // Delete all the order line records
102
String deleteLineSQL = "delete from " + orderlinesTable + " where " +
103                 "olwid = '" + pk.ivWarehouseID + "' " +
104                 "and oldid = " + pk.ivDistrictID + " " +
105                 "and oloid = " + pk.ivOrderID;
106             stmt = con.createStatement();
107             int lineCount = stmt.executeUpdate(deleteLineSQL);
108             if (lineCount == 0) {
109                 throw new RemoveException ("Failed to delete bean from database lineCount == 0");
110             }
111             stmt.close();
112         
113             // Delete the order record
114
String deleteOrderSQL = "delete from " + ordersTable + " where " +
115                 "owid = '" + pk.ivWarehouseID + "' " +
116                 "and odid = " + pk.ivDistrictID + " " +
117                 "and ooid = " + pk.ivOrderID;
118             stmt = con.createStatement();
119             int orderCount = stmt.executeUpdate(deleteOrderSQL);
120             stmt.close();
121             if (orderCount == 0) {
122                 throw new RemoveException ("Failed to delete" + ivOrderID + ") from database lineCount == 0");
123             }
124         
125         } catch (SQLException sqe) {
126             throw new RemoveException (sqe.getMessage());
127         } finally {
128             try {
129                 con.close();
130             } catch (Exception ignore) {}
131         }
132         
133     }
134
135     public void ejbLoad() {
136         logger.log(BasicLevel.DEBUG, "");
137         //Get the primary key from the context object.
138
OrderID pk = (OrderID) ctx.getPrimaryKey();
139     
140         Connection con = null;
141         Statement stmt = null;
142         
143         try{
144             con = getConnection();
145             
146             // Create a new Vector to hold order lines.
147
// Retrieve all the order lines that match the supplied primary key.
148
// For each order line, create a new OrderDetail object and store it on the Vector.
149
// Replace the existing ivOrderItems with the new Vector
150

151             Vector newOrderLines = new Vector();
152             String selectLineSQL = "select * from " + orderlinesTable + " where " +
153                 "olwid = '" + pk.ivWarehouseID + "' " +
154                 "and oldid = " + pk.ivDistrictID + " " +
155                 "and oloid = " + pk.ivOrderID;
156             stmt = con.createStatement();
157             ResultSet rsLines = stmt.executeQuery(selectLineSQL);
158             while(rsLines.next()){
159                 Integer itemID = new Integer(rsLines.getInt("OLIID"));
160                 float amount = rsLines.getFloat("OLAMNT");
161                 int qty = rsLines.getInt("OLQTY");
162                 int lineNumber = rsLines.getInt("OLNBR");
163                 OrderDetail od = new OrderDetail(itemID, amount, qty);
164                 od.setLineNumber(lineNumber);
165                 newOrderLines.addElement(od);
166             }
167             rsLines.close();
168             stmt.close();
169             
170             ivOrderItems = newOrderLines;
171             ivNumberOfOrderLines = ivOrderItems.size();
172             
173             // Retrieve the order header information from the orders table and
174
// replace the order instance variables
175
//
176
String selectOrderSQL = "select * from " + ordersTable + " where " +
177                 "owid = '" + pk.ivWarehouseID + "' " +
178                 "and odid = " + pk.ivDistrictID + " " +
179                 "and ooid = " + pk.ivOrderID;
180             stmt = con.createStatement();
181             ResultSet rsOrder = stmt.executeQuery(selectOrderSQL);
182             if(rsOrder.next()){
183                 ivWarehouseID = pk.ivWarehouseID;
184                 ivDistrictID = pk.ivDistrictID;
185                 ivCustomerID = new Integer(rsOrder.getInt("ocid"));
186                 ivOrderID = pk.ivOrderID;
187             }else{
188                 throw new EJBException("Order " + pk.ivOrderID + " not found.");
189             }
190             rsOrder.close();
191             stmt.close();
192             setModified(false);
193         } catch (SQLException sqe){
194             throw new EJBException(sqe.getMessage());
195         } finally {
196             try {
197                 con.close();
198             }catch (Exception ignore) {}
199         }
200     }
201  
202
203     public void ejbStore() {
204         logger.log(BasicLevel.DEBUG, "");
205         if ( !isModified() )
206             return;
207         Connection con = null;
208         PreparedStatement ps = null;
209         Statement stmt = null;
210         try {
211             con = getConnection();
212         
213             // Create an sql prepared statement that will be used for each order line.
214
// The modifiable values are item id (oliid), qty (olqty), and price (olamnt).
215
ps = con.prepareStatement("update ordlin set oliid = ?, olqty = ?, olamnt = ? " +
216                                       "where oloid = " + ivOrderID + " " +
217                                       "and oldid = " + ivDistrictID + " " +
218                                       "and olwid = '" + ivWarehouseID + "' " +
219                                       "and olnbr = ?");
220         
221             // Iterate through each order line and update the record into the database
222
Enumeration enum = ivOrderItems.elements();
223             while(enum.hasMoreElements()){
224                 OrderDetail od = (OrderDetail)enum.nextElement();
225                 ps.setInt(1, od.getItemID().intValue());
226                 ps.setInt(2, od.getItemQty());
227                 ps.setFloat(3, od.getItemAmount());
228                 ps.setInt(4, od.getLineNumber());
229                 int lineCount = ps.executeUpdate();
230                 if (lineCount == 0) {
231                     throw new EJBException("ejbStore: OrderBean (" + ivOrderID + ") not updated");
232                 }
233             }
234         
235             // Update the order table record
236
// The modifiable values are customer id (ocid) and number of order lines (olines).
237
String updateSQL = "update " + ordersTable + " set " +
238                 "ocid = '" + ivCustomerID + "', " +
239                 "olines = " + ivNumberOfOrderLines + " " +
240                 "where owid = '" + ivWarehouseID + "' " +
241                 "and odid = " + ivDistrictID + " " +
242                 "and ooid = " + ivOrderID;
243         
244             stmt = con.createStatement();
245             int orderCount = stmt.executeUpdate(updateSQL);
246             if (orderCount == 0) {
247                 throw new EJBException("ejbStore: OrderBean (" + ivOrderID + ") not updated");
248             }
249         
250         
251             setModified(false);
252         
253         } catch (SQLException sqe) {
254             throw new EJBException(sqe.getMessage());
255         } finally {
256             try{
257                 stmt.close();
258                 ps.close();
259                 con.close();
260             } catch (Exception ignore){}
261         }
262
263     }
264
265
266     public void ejbPassivate() {
267         logger.log(BasicLevel.DEBUG, "");
268     }
269
270
271     public void ejbActivate() {
272         logger.log(BasicLevel.DEBUG, "");
273     }
274
275     public void ejbPostCreate(String warehouseID,
276                               int districtID, Integer customerID,
277                              float orderID, Vector orderItems){
278         logger.log(BasicLevel.DEBUG, "");
279     }
280
281
282     /**
283      * This method is called when a client calls the OrderHome.create(). It creates
284      * records in the database for the line items and the order header information.
285      * @param warehouseID String Warehouse ID
286      * @param districtID int District ID
287      * @param customerID Integer Customer ID
288      * @param orderID float Order ID - NOTE: must be passed in as parameter, it is not created by the bean
289      * @param orderItems Vector of OrderDetail objects. Each OrderDetail object represents one line item on the order. The bean determines the order line number.
290      * @exception javax.ejb.CreateException
291      * @exception javax.ejb.RemoteException
292      */

293     /* Use separate conneciton objects for ordlin and orders */
294     public OrderID ejbCreate(String warehouseID, int districtID, Integer customerID,
295                              float orderID, Vector orderItems)
296         throws CreateException, RemoteException {
297         logger.log(BasicLevel.DEBUG, "");
298         ivWarehouseID = warehouseID;
299         ivDistrictID = districtID;
300         ivCustomerID = customerID;
301         ivOrderID = orderID;
302         ivNumberOfOrderLines = orderItems.size();
303         ivOrderItems = orderItems;
304         // Use JDBC to store the Order to the database
305
Connection con = null;
306         try {
307             con = getConnection();
308             // Iterate through each order line and insert a record into the database
309
int orderLineNumber = 1;
310             Enumeration enum = ivOrderItems.elements();
311             while(enum.hasMoreElements()){
312                 OrderDetail od = (OrderDetail)enum.nextElement();
313                 String orderlineSQL = "insert into " + orderlinesTable +" (OLOID, OLDID, OLWID, OLNBR, OLIID, OLQTY, OLAMNT) " +
314                     "values (" + ivOrderID +
315                     ", " + ivDistrictID +
316                     ", '" + ivWarehouseID + "'" +
317                     ", " + orderLineNumber +
318                     ", '" + od.getItemID() + "'" +
319                     ", " + od.getItemQty() +
320                     ", " + od.getItemAmount() + ")";
321                 Statement stmtLine = con.createStatement();
322                 logger.log(BasicLevel.DEBUG, "orderlineSQL= "+orderlineSQL);
323                 int lineCount = stmtLine.executeUpdate(orderlineSQL);
324                 if (lineCount == 0) {
325                     logger.log(BasicLevel.DEBUG, "lineCount == 0");
326                     throw new CreateException ("Unable to create order line item: " + orderLineNumber);
327                 }
328                 stmtLine.close();
329                 od.setLineNumber(orderLineNumber); //Store the line number in the order detail object.
330
orderLineNumber++;
331             }
332         
333             // Insert a record into the order table
334
String insertSQL = "insert into " + ordersTable +
335                  "(OWID, ODID, OCID, OOID, OLINES) values (" +
336                 "'" + ivWarehouseID + "', " +
337                 ivDistrictID + ", " +
338                 "'" + ivCustomerID + "', " +
339                 ivOrderID + ", " +
340                 ivNumberOfOrderLines +
341                 ")";
342             Statement stmtOrder = con.createStatement();
343             logger.log(BasicLevel.DEBUG, "insertSQL= "+insertSQL);
344             int orderCount = stmtOrder.executeUpdate(insertSQL);
345             if (orderCount == 0) {
346                 throw new CreateException ("Unable to create order");
347             }
348             stmtOrder.close();
349         
350             // Create the primary key
351
OrderID oID = new OrderID(ivWarehouseID, ivDistrictID, ivOrderID);
352         
353             return oID;
354         
355         
356         } catch (CreateException ce) {
357             System.out.println("CreateException thrown: " + ce.getMessage());
358             throw ce;
359         } catch (SQLException sqe) {
360             System.out.println("SQLException thrown: " + sqe.getMessage());
361             throw new CreateException (sqe.getMessage());
362         } finally {
363             try{
364                 con.close();
365             } catch (Exception ignore){}
366         }
367                     
368
369
370     }
371
372     public OrderID ejbFindByPrimaryKey(OrderID pk) throws FinderException {
373         logger.log(BasicLevel.DEBUG, "");
374         if ( pk == null ) {
375             throw new FinderException("ejbFindByPrimaryKey: null primary key");
376         }
377
378         Connection con = null;
379         Statement stmt = null;
380         
381         try{
382             con = getConnection();
383             // Find the order in the orders table
384
String selectOrderSQL = "select * from " + ordersTable + " where " +
385                 "owid = '" + pk.ivWarehouseID + "' " +
386                 "and odid = " + pk.ivDistrictID + " " +
387                 "and ooid = " + pk.ivOrderID;
388             stmt = con.createStatement();
389             ResultSet rsOrder = stmt.executeQuery(selectOrderSQL);
390             if(rsOrder.next()){
391                 //Order found, don't throw exception
392
}else{
393                 //Order not fount, throw exception
394
throw new FinderException("Order " + pk.ivOrderID + " not found.");
395             }
396             rsOrder.close();
397             stmt.close();
398             
399         } catch (SQLException sqe){
400             //Unable to find the order because of an SQL error.
401
throw new FinderException (sqe.getMessage());
402         } finally {
403             try {
404                 con.close();
405             }catch (Exception ignore) {}
406         }
407         return pk;
408  
409     }
410
411      /**
412      * Finds an order given the warehouse, district and order IDs as Strings.
413      * The method constructs an OrderID from the three parameters and calls
414      * ejbFindByPrimaryKey().
415      *
416      * @param wID String Warehouse ID
417      * @param dID String District ID
418      * @param oID String Order ID
419      *
420      * @exception java.rmi.RemoteException
421      * @exception javax.ejb.FinderException
422      * thrown if the EJBean cannot be found.
423      */

424     public OrderID ejbFindByID(String wID, String dID, String oID)
425     throws FinderException, RemoteException {
426                         
427     OrderID pk = new OrderID(wID, dID, oID);
428     return ejbFindByPrimaryKey(pk);
429                         
430     }
431
432     private Connection getConnection() throws SQLException {
433         if (dataSource == null) {
434             // Finds DataSource from JNDI
435
try {
436                 initialContext = new InitialContext();
437                 dataSource = (DataSource)initialContext.lookup("java:comp/env/jdbc/Order");
438             } catch (Exception e) {
439                 logger.log(BasicLevel.ERROR, "Pb with naming context");
440                 throw new javax.ejb.EJBException("Pb with naming context ");
441             }
442         }
443         return dataSource.getConnection();
444     }
445
446     private Context initialContext = null;
447     // ------------------------------------------------------------------
448
// Order implementation
449
// ------------------------------------------------------------------
450

451     // *********************************************************************** //
452
// Implementation of business methods defined in Order interface
453
// *********************************************************************** //
454

455     public Integer getCustomerID() throws RemoteException {
456         return ivCustomerID;
457     }
458     public int getOrderLineCount() throws RemoteException {
459         return ivNumberOfOrderLines;
460     }
461     public Vector getOrderItems() throws RemoteException {
462         return ivOrderItems;
463     }
464  
465 }
466
467
468
469
Popular Tags