package dbj.odmg; import COM.POET.odmg.*; import COM.POET.odmg.collection.*; import java.util.*; import java.io.*; public class CreateOrder { Database dbase; public CreateOrder (Database db) { dbase = db; } private Customer findCustomer (int custId) throws ODMGException { Customer cust = null; String queryString = "SELECT c FROM CustomerExtent as c WHERE c.id_ = $1"; OQLQuery query = new OQLQuery (queryString); query.bind (new Integer (custId)); Object result = query.execute (); CollectionOfObject coll = (CollectionOfObject) result; Enumeration e = coll.elements (); if (e.hasMoreElements ()) cust = (Customer) e.nextElement (); return cust; } private Book findBook (String isbn) throws ODMGException { Book book = null; String queryString = "SELECT b FROM BookExtent as b WHERE b.isbn_ = $1"; OQLQuery query = new OQLQuery (queryString); query.bind (isbn); Object result = query.execute (); CollectionOfObject coll = (CollectionOfObject) result; Enumeration e = coll.elements (); if (e.hasMoreElements ()) book = (Book) e.nextElement (); return book; } public void create (int custId) throws ODMGException { BagOfObject orders; boolean ready = false, valid = false; Transaction tx = new Transaction (); tx.begin (); try { orders = (BagOfObject) dbase.lookup ("orders"); Customer customer = findCustomer (custId); if (customer == null) { System.out.println ("unknown customer: " + custId); tx.abort (); return; } BookOrder order = new BookOrder (); do { String isbn = Utils.readString ("isbn: "); if (isbn == null || isbn.length () == 0) ready = true; else { int num = Utils.readInt ("number: "); if (num > 0) { Book book = findBook (isbn); if (book == null) { System.out.println ("cannot find book: " + isbn); continue; } order.addItem (book, num); valid = true; } } } while (! ready); if (valid) { order.setCustomer (customer); orders.add (order); } } catch (ObjectNameNotFoundException e) { System.out.println ("fatal error: orders not found !"); tx.abort (); throw e; } catch (ODMGException exc) { tx.abort (); throw exc; } tx.commit (); } public static void main (String args[]) throws IOException { if (args.length != 1) { System.out.println ("usage: dbj.odmg.CreateOrder custId"); System.exit (1); } Properties props = new Properties (); props.load (new FileInputStream ("dbj.properties")); try { Database db = Database.open (props.getProperty ("odmg.database"), Database.openReadWrite); CreateOrder app = new CreateOrder (db); app.create (Integer.parseInt (args[0])); } catch (Exception exc) { exc.printStackTrace (); } } }