1// File: ExampleDatabaseRead
2
3package db.GettingStarted;
4
5import com.sleepycat.bind.EntryBinding;
6import com.sleepycat.bind.serial.SerialBinding;
7import com.sleepycat.bind.tuple.TupleBinding;
8import com.sleepycat.db.Cursor;
9import com.sleepycat.db.DatabaseEntry;
10import com.sleepycat.db.DatabaseException;
11import com.sleepycat.db.LockMode;
12import com.sleepycat.db.OperationStatus;
13import com.sleepycat.db.SecondaryCursor;
14
15import java.io.IOException;
16
17public class ExampleDatabaseRead {
18
19    private static String myDbsPath = "./";
20
21    // Encapsulates the database environment and databases.
22    private static MyDbs myDbs = new MyDbs();
23
24    private static TupleBinding inventoryBinding;
25    private static EntryBinding vendorBinding;
26
27    // The item to locate if the -s switch is used
28    private static String locateItem;
29
30    private static void usage() {
31        System.out.println("ExampleDatabaseRead [-h <env directory>]" +
32                           "[-s <item to locate>]");
33        System.exit(-1);
34    }
35
36    public static void main(String args[]) {
37        ExampleDatabaseRead edr = new ExampleDatabaseRead();
38        try {
39            edr.run(args);
40        } catch (DatabaseException dbe) {
41            System.err.println("ExampleDatabaseRead: " + dbe.toString());
42            dbe.printStackTrace();
43        } finally {
44            myDbs.close();
45        }
46        System.out.println("All done.");
47    }
48
49    private void run(String args[])
50        throws DatabaseException {
51        // Parse the arguments list
52        parseArgs(args);
53
54        myDbs.setup(myDbsPath);
55
56        // Setup our bindings.
57        inventoryBinding = new InventoryBinding();
58        vendorBinding =
59             new SerialBinding(myDbs.getClassCatalog(),
60                               Vendor.class);
61
62        if (locateItem != null) {
63            showItem();
64        } else {
65            showAllInventory();
66        }
67    }
68
69    private void showItem() throws DatabaseException {
70
71        SecondaryCursor secCursor = null;
72        try {
73            // searchKey is the key that we want to find in the
74            // secondary db.
75            DatabaseEntry searchKey =
76                new DatabaseEntry(locateItem.getBytes("UTF-8"));
77
78            // foundKey and foundData are populated from the primary
79            // entry that is associated with the secondary db key.
80            DatabaseEntry foundKey = new DatabaseEntry();
81            DatabaseEntry foundData = new DatabaseEntry();
82
83            // open a secondary cursor
84            secCursor =
85                myDbs.getNameIndexDB().openSecondaryCursor(null, null);
86
87            // Search for the secondary database entry.
88            OperationStatus retVal =
89                secCursor.getSearchKey(searchKey, foundKey,
90                    foundData, LockMode.DEFAULT);
91
92            // Display the entry, if one is found. Repeat until no more
93            // secondary duplicate entries are found
94            while(retVal == OperationStatus.SUCCESS) {
95                Inventory theInventory =
96                    (Inventory)inventoryBinding.entryToObject(foundData);
97                displayInventoryRecord(foundKey, theInventory);
98                retVal = secCursor.getNextDup(searchKey, foundKey,
99                    foundData, LockMode.DEFAULT);
100            }
101        } catch (Exception e) {
102            System.err.println("Error on inventory secondary cursor:");
103            System.err.println(e.toString());
104            e.printStackTrace();
105        } finally {
106            if (secCursor != null) {
107                secCursor.close();
108            }
109        }
110    }
111
112    private void showAllInventory()
113        throws DatabaseException {
114        // Get a cursor
115        Cursor cursor = myDbs.getInventoryDB().openCursor(null, null);
116
117        // DatabaseEntry objects used for reading records
118        DatabaseEntry foundKey = new DatabaseEntry();
119        DatabaseEntry foundData = new DatabaseEntry();
120
121        try { // always want to make sure the cursor gets closed
122            while (cursor.getNext(foundKey, foundData,
123                        LockMode.DEFAULT) == OperationStatus.SUCCESS) {
124                Inventory theInventory =
125                    (Inventory)inventoryBinding.entryToObject(foundData);
126                displayInventoryRecord(foundKey, theInventory);
127            }
128        } catch (Exception e) {
129            System.err.println("Error on inventory cursor:");
130            System.err.println(e.toString());
131            e.printStackTrace();
132        } finally {
133            cursor.close();
134        }
135    }
136
137    private void displayInventoryRecord(DatabaseEntry theKey,
138                                        Inventory theInventory)
139        throws DatabaseException {
140
141        String theSKU = new String(theKey.getData());
142        System.out.println(theSKU + ":");
143        System.out.println("\t " + theInventory.getItemName());
144        System.out.println("\t " + theInventory.getCategory());
145        System.out.println("\t " + theInventory.getVendor());
146        System.out.println("\t\tNumber in stock: " +
147            theInventory.getVendorInventory());
148        System.out.println("\t\tPrice per unit:  " +
149            theInventory.getVendorPrice());
150        System.out.println("\t\tContact: ");
151
152        DatabaseEntry searchKey = null;
153        try {
154            searchKey =
155                new DatabaseEntry(theInventory.getVendor().getBytes("UTF-8"));
156        } catch (IOException willNeverOccur) {}
157        DatabaseEntry foundVendor = new DatabaseEntry();
158
159        if (myDbs.getVendorDB().get(null, searchKey, foundVendor,
160                LockMode.DEFAULT) != OperationStatus.SUCCESS) {
161            System.out.println("Could not find vendor: " +
162                theInventory.getVendor() + ".");
163            System.exit(-1);
164        } else {
165            Vendor theVendor =
166                (Vendor)vendorBinding.entryToObject(foundVendor);
167            System.out.println("\t\t " + theVendor.getAddress());
168            System.out.println("\t\t " + theVendor.getCity() + ", " +
169                theVendor.getState() + " " + theVendor.getZipcode());
170            System.out.println("\t\t Business Phone: " +
171                theVendor.getBusinessPhoneNumber());
172            System.out.println("\t\t Sales Rep: " +
173                                theVendor.getRepName());
174            System.out.println("\t\t            " +
175                theVendor.getRepPhoneNumber());
176       }
177    }
178
179    protected ExampleDatabaseRead() {}
180
181    private static void parseArgs(String args[]) {
182        for(int i = 0; i < args.length; ++i) {
183            if (args[i].startsWith("-")) {
184                switch(args[i].charAt(1)) {
185                    case 'h':
186                        myDbsPath = new String(args[++i]);
187                        break;
188                    case 's':
189                        locateItem = new String(args[++i]);
190                    break;
191                    default:
192                        usage();
193                }
194            }
195        }
196    }
197}
198