1 /*-
2  * See the file LICENSE for redistribution information.
3  *
4  * Copyright (c) 2002, 2014 Oracle and/or its affiliates.  All rights reserved.
5  *
6  */
7 
8 package collections.ship.entity;
9 
10 import java.util.Iterator;
11 import java.util.Set;
12 
13 import com.sleepycat.collections.TransactionRunner;
14 import com.sleepycat.collections.TransactionWorker;
15 import com.sleepycat.je.DatabaseException;
16 
17 /**
18  * Sample is the main entry point for the sample program and may be run as
19  * follows:
20  *
21  * <pre>
22  * java collections.ship.entity.Sample
23  *      [-h <home-directory> ]
24  * </pre>
25  *
26  * <p> The default for the home directory is ./tmp -- the tmp subdirectory of
27  * the current directory where the sample is run. The home directory must exist
28  * before running the sample.  To recreate the sample database from scratch,
29  * delete all files in the home directory before running the sample.  </p>
30  *
31  * @author Mark Hayes
32  */
33 public class Sample {
34 
35     private final SampleDatabase db;
36     private final SampleViews views;
37 
38     /**
39      * Run the sample program.
40      */
main(String[] args)41     public static void main(String[] args) {
42 
43         System.out.println("\nRunning sample: " + Sample.class);
44 
45         // Parse the command line arguments.
46         //
47         String homeDir = "./tmp";
48         for (int i = 0; i < args.length; i += 1) {
49             if (args[i].equals("-h") && i < args.length - 1) {
50                 i += 1;
51                 homeDir = args[i];
52             } else {
53                 System.err.println("Usage:\n java " + Sample.class.getName() +
54                                    "\n  [-h <home-directory>]");
55                 System.exit(2);
56             }
57         }
58 
59         // Run the sample.
60         //
61         Sample sample = null;
62         try {
63             sample = new Sample(homeDir);
64             sample.run();
65         } catch (Exception e) {
66             // If an exception reaches this point, the last transaction did not
67             // complete.  If the exception is RunRecoveryException, follow
68             // the Berkeley DB recovery procedures before running again.
69             e.printStackTrace();
70         } finally {
71             if (sample != null) {
72                 try {
73                     // Always attempt to close the database cleanly.
74                     sample.close();
75                 } catch (Exception e) {
76                     System.err.println("Exception during database close:");
77                     e.printStackTrace();
78                 }
79             }
80         }
81     }
82 
83     /**
84      * Open the database and views.
85      */
Sample(String homeDir)86     private Sample(String homeDir)
87         throws DatabaseException {
88 
89         db = new SampleDatabase(homeDir);
90         views = new SampleViews(db);
91     }
92 
93     /**
94      * Close the database cleanly.
95      */
close()96     private void close()
97         throws DatabaseException {
98 
99         db.close();
100     }
101 
102     /**
103      * Run two transactions to populate and print the database.  A
104      * TransactionRunner is used to ensure consistent handling of transactions,
105      * including deadlock retries.  But the best transaction handling mechanism
106      * to use depends on the application.
107      */
run()108     private void run()
109         throws Exception {
110 
111         TransactionRunner runner = new TransactionRunner(db.getEnvironment());
112         runner.run(new PopulateDatabase());
113         runner.run(new PrintDatabase());
114     }
115 
116     /**
117      * Populate the database in a single transaction.
118      */
119     private class PopulateDatabase implements TransactionWorker {
120 
doWork()121         public void doWork() {
122             addSuppliers();
123             addParts();
124             addShipments();
125         }
126     }
127 
128     /**
129      * Print the database in a single transaction.  All entities are printed
130      * and the indices are used to print the entities for certain keys.
131      *
132      * <p> Note the use of special iterator() methods.  These are used here
133      * with indices to find the shipments for certain keys.</p>
134      */
135     private class PrintDatabase implements TransactionWorker {
136 
doWork()137         public void doWork() {
138             printValues("Parts",
139                         views.getPartSet().iterator());
140             printValues("Suppliers",
141                         views.getSupplierSet().iterator());
142             printValues("Suppliers for City Paris",
143                         views.getSupplierByCityMap().duplicates(
144                                             "Paris").iterator());
145             printValues("Shipments",
146                         views.getShipmentSet().iterator());
147             printValues("Shipments for Part P1",
148                         views.getShipmentByPartMap().duplicates(
149                                             new PartKey("P1")).iterator());
150             printValues("Shipments for Supplier S1",
151                         views.getShipmentBySupplierMap().duplicates(
152                                             new SupplierKey("S1")).iterator());
153         }
154     }
155 
156     /**
157      * Populate the part entities in the database.  If the part set is not
158      * empty, assume that this has already been done.
159      */
addParts()160     private void addParts() {
161 
162         Set parts = views.getPartSet();
163         if (parts.isEmpty()) {
164             System.out.println("Adding Parts");
165             parts.add(new Part("P1", "Nut", "Red",
166                                new Weight(12.0, Weight.GRAMS), "London"));
167             parts.add(new Part("P2", "Bolt", "Green",
168                                new Weight(17.0, Weight.GRAMS), "Paris"));
169             parts.add(new Part("P3", "Screw", "Blue",
170                                new Weight(17.0, Weight.GRAMS), "Rome"));
171             parts.add(new Part("P4", "Screw", "Red",
172                                new Weight(14.0, Weight.GRAMS), "London"));
173             parts.add(new Part("P5", "Cam", "Blue",
174                                new Weight(12.0, Weight.GRAMS), "Paris"));
175             parts.add(new Part("P6", "Cog", "Red",
176                                new Weight(19.0, Weight.GRAMS), "London"));
177         }
178     }
179 
180     /**
181      * Populate the supplier entities in the database.  If the supplier set is
182      * not empty, assume that this has already been done.
183      */
addSuppliers()184     private void addSuppliers() {
185 
186         Set suppliers = views.getSupplierSet();
187         if (suppliers.isEmpty()) {
188             System.out.println("Adding Suppliers");
189             suppliers.add(new Supplier("S1", "Smith", 20, "London"));
190             suppliers.add(new Supplier("S2", "Jones", 10, "Paris"));
191             suppliers.add(new Supplier("S3", "Blake", 30, "Paris"));
192             suppliers.add(new Supplier("S4", "Clark", 20, "London"));
193             suppliers.add(new Supplier("S5", "Adams", 30, "Athens"));
194         }
195     }
196 
197     /**
198      * Populate the shipment entities in the database.  If the shipment set
199      * is not empty, assume that this has already been done.
200      */
addShipments()201     private void addShipments() {
202 
203         Set shipments = views.getShipmentSet();
204         if (shipments.isEmpty()) {
205             System.out.println("Adding Shipments");
206             shipments.add(new Shipment("P1", "S1", 300));
207             shipments.add(new Shipment("P2", "S1", 200));
208             shipments.add(new Shipment("P3", "S1", 400));
209             shipments.add(new Shipment("P4", "S1", 200));
210             shipments.add(new Shipment("P5", "S1", 100));
211             shipments.add(new Shipment("P6", "S1", 100));
212             shipments.add(new Shipment("P1", "S2", 300));
213             shipments.add(new Shipment("P2", "S2", 400));
214             shipments.add(new Shipment("P2", "S3", 200));
215             shipments.add(new Shipment("P2", "S4", 200));
216             shipments.add(new Shipment("P4", "S4", 300));
217             shipments.add(new Shipment("P5", "S4", 400));
218         }
219     }
220 
221     /**
222      * Print the objects returned by an iterator of entity value objects.
223      */
printValues(String label, Iterator iterator)224     private void printValues(String label, Iterator iterator) {
225 
226         System.out.println("\n--- " + label + " ---");
227         while (iterator.hasNext()) {
228             System.out.println(iterator.next().toString());
229         }
230     }
231 }
232