1<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3<html xmlns="http://www.w3.org/1999/xhtml">
4  <head>
5    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
6    <title>Cursor Example</title>
7    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
8    <meta name="generator" content="DocBook XSL Stylesheets V1.62.4" />
9    <link rel="home" href="index.html" title="Getting Started with Berkeley DB" />
10    <link rel="up" href="Cursors.html" title="Chapter��9.��Using Cursors" />
11    <link rel="previous" href="ReplacingEntryWCursor.html" title="Replacing Records Using Cursors" />
12    <link rel="next" href="indexes.html" title="Chapter��10.��Secondary Databases" />
13  </head>
14  <body>
15    <div class="navheader">
16      <table width="100%" summary="Navigation header">
17        <tr>
18          <th colspan="3" align="center">Cursor Example</th>
19        </tr>
20        <tr>
21          <td width="20%" align="left"><a accesskey="p" href="ReplacingEntryWCursor.html">Prev</a>��</td>
22          <th width="60%" align="center">Chapter��9.��Using Cursors</th>
23          <td width="20%" align="right">��<a accesskey="n" href="indexes.html">Next</a></td>
24        </tr>
25      </table>
26      <hr />
27    </div>
28    <div class="sect1" lang="en" xml:lang="en">
29      <div class="titlepage">
30        <div>
31          <div>
32            <h2 class="title" style="clear: both"><a id="cursorJavaUsage"></a>Cursor Example</h2>
33          </div>
34        </div>
35        <div></div>
36      </div>
37      <p>In <a href="dbtJavaUsage.html">Database Usage Example</a> we wrote an
38    application that loaded two <tt class="classname">Database</tt> objects with vendor
39    and inventory information. In this example, we will use those databases to
40    display all of the items in the inventory database. As a part of showing
41    any given inventory item, we will look up the vendor who can provide the
42    item and show the vendor's contact information.</p>
43      <p>To do this, we create the <tt class="classname">ExampleDatabaseRead</tt>
44    application. This application reads and displays all inventory records by:</p>
45      <div class="orderedlist">
46        <ol type="1">
47          <li>
48            <p>Opening the  inventory, vendor, and
49        class catalog <tt class="classname">Database</tt> objects. We do this using the
50        <tt class="classname">MyDbs</tt> class. See <a href="dbtJavaUsage.html#dbsStoredClass">Stored Class Catalog Management with MyDbs</a>
51        for a description of this class.</p>
52          </li>
53          <li>
54            <p>Obtaining a cursor from the inventory <tt class="classname">Database</tt>.</p>
55          </li>
56          <li>
57            <p>Steps through the <tt class="classname">Database</tt>, displaying
58        each record as it goes.</p>
59          </li>
60          <li>
61            <p>To display the Inventory record, the custom tuple binding that
62        we created in <a href="dbtJavaUsage.html#InventoryJavaBinding">InventoryBinding.java</a> is used.</p>
63          </li>
64          <li>
65            <p><tt class="methodname">Database.get()</tt> is used to obtain the vendor that corresponds to
66        the inventory item.</p>
67          </li>
68          <li>
69            <p>A serial binding is used to convert the
70        <tt class="classname">DatabaseEntry</tt> returned
71        by the <tt class="methodname">get()</tt> to a Vendor object.</p>
72          </li>
73          <li>
74            <p>The contents of the Vendor object are displayed.</p>
75          </li>
76        </ol>
77      </div>
78      <p>We implemented the <tt class="classname">Vendor</tt> class in <a href="dbtJavaUsage.html#vendorjava">Vendor.java</a>. We implemented the
79    <tt class="classname">Inventory</tt> class in <a href="dbtJavaUsage.html#inventoryjava">Inventory.java</a>.</p>
80      <p>The full implementation of <tt class="classname">ExampleDatabaseRead</tt>
81    can be found in:
82    </p>
83      <pre class="programlisting"><span class="emphasis"><em>DB_INSTALL</em></span>/examples_java/db/GettingStarted</pre>
84      <p>
85        where <tt class="literal"><span class="emphasis"><em>DB_INSTALL</em></span></tt> is the location where you
86        placed your DB distribution.
87    </p>
88      <div class="example">
89        <a id="EDR"></a>
90        <p class="title">
91          <b>Example 9.1 ExampleDatabaseRead.java</b>
92        </p>
93        <p>To begin, we import the necessary classes:</p>
94        <a id="java_cursor10"></a>
95        <pre class="programlisting">// file ExampleDatabaseRead.java
96package db.GettingStarted;
97
98import java.io.File;
99import java.io.IOException;
100
101import com.sleepycat.bind.EntryBinding;
102import com.sleepycat.bind.serial.SerialBinding;
103import com.sleepycat.bind.tuple.TupleBinding;
104import com.sleepycat.db.Cursor;
105import com.sleepycat.db.DatabaseEntry;
106import com.sleepycat.db.DatabaseException;
107import com.sleepycat.db.LockMode;
108import com.sleepycat.db.OperationStatus;</pre>
109        <p>Next we declare our class and set up some global variables. Note a
110      <tt class="classname">MyDbs</tt> object is instantiated here. We can do
111      this because its constructor never throws an exception. See <a href="CoreJavaUsage.html">Database Example</a> for its implementation
112      details.</p>
113        <a id="java_cursor11"></a>
114        <pre class="programlisting">public class ExampleDatabaseRead {
115
116    private static String myDbsPath = "./";
117
118    // Encapsulates the database environment and databases.
119    private static MyDbs myDbs = new MyDbs();
120
121    private static TupleBinding inventoryBinding;
122    private static EntryBinding vendorBinding; </pre>
123        <p>
124        Next we create the <tt class="methodname">ExampleDatabaseRead.usage()</tt> and
125        <tt class="methodname">ExampleDatabaseRead.main()</tt> methods. 
126        We perform almost all of our exception handling from <tt class="methodname">ExampleDatabaseRead.main()</tt>, and so we
127        must catch <tt class="classname">DatabaseException</tt> because the <tt class="literal">com.sleepycat.db.*</tt>
128        APIs throw them.
129      </p>
130        <a id="java_cursor12"></a>
131        <pre class="programlisting">   private static void usage() {
132        System.out.println("ExampleDatabaseRead [-h &lt;env directory&gt;]" +
133                           "[-s &lt;item to locate&gt;]");
134        System.exit(-1);
135    }
136
137    public static void main(String args[]) {
138        ExampleDatabaseRead edr = new ExampleDatabaseRead();
139        try {
140            edr.run(args);
141        } catch (DatabaseException dbe) {
142            System.err.println("ExampleDatabaseRead: " + dbe.toString());
143            dbe.printStackTrace();
144        } finally {
145            myDbs.close();
146        }
147        System.out.println("All done.");
148    }</pre>
149        <p>In <tt class="methodname">ExampleDatabaseRead.run()</tt>, we call <tt class="methodname">MyDbs.setup()</tt> to
150      open our databases. Then we create the bindings that we need for using our data objects with 
151      <tt class="classname">DatabaseEntry</tt> objects.
152      </p>
153        <a id="java_cursor13"></a>
154        <pre class="programlisting">    private void run(String args[])
155        throws DatabaseException {
156        // Parse the arguments list
157        parseArgs(args);
158
159        myDbs.setup(myDbsPath);
160
161        // Setup our bindings.
162        inventoryBinding = new InventoryBinding();
163        vendorBinding =
164             new SerialBinding(myDbs.getClassCatalog(),
165                               Vendor.class);
166
167        showAllInventory();
168    }</pre>
169        <p>Now we write the loop that displays the <tt class="classname">Inventory</tt>
170      records. We do this by opening a cursor on the inventory database and
171      iterating over all its contents, displaying each as we go.</p>
172        <a id="java_cursor14"></a>
173        <pre class="programlisting">    private void showAllInventory() 
174        throws DatabaseException {
175        // Get a cursor
176        Cursor cursor = myDbs.getInventoryDB().openCursor(null, null);
177
178        // DatabaseEntry objects used for reading records
179        DatabaseEntry foundKey = new DatabaseEntry();
180        DatabaseEntry foundData = new DatabaseEntry();
181                                                                                                                                       
182        try { // always want to make sure the cursor gets closed
183            while (cursor.getNext(foundKey, foundData,
184                        LockMode.DEFAULT) == OperationStatus.SUCCESS) {
185                Inventory theInventory =
186                    (Inventory)inventoryBinding.entryToObject(foundData);
187                displayInventoryRecord(foundKey, theInventory);
188            }
189        } catch (Exception e) {
190            System.err.println("Error on inventory cursor:");
191            System.err.println(e.toString());
192            e.printStackTrace();
193        } finally {
194            cursor.close();
195        }
196    } </pre>
197        <p>We use <tt class="methodname">ExampleDatabaseRead.displayInventoryRecord()</tt> 
198       to actually show the record. This
199      method first displays all the relevant information from the retrieved
200      Inventory object. It then uses the vendor database to retrieve and
201      display the vendor. Because the vendor database is keyed by vendor name,
202      and because each inventory object contains this key, it is trivial to
203      retrieve the appropriate vendor record.</p>
204        <a id="java_cursor15"></a>
205        <pre class="programlisting">   private void displayInventoryRecord(DatabaseEntry theKey,
206                                        Inventory theInventory)
207        throws DatabaseException {
208
209        String theSKU = new String(theKey.getData(), "UTF-8");
210        System.out.println(theSKU + ":");
211        System.out.println("\t " + theInventory.getItemName());
212        System.out.println("\t " + theInventory.getCategory());
213        System.out.println("\t " + theInventory.getVendor());
214        System.out.println("\t\tNumber in stock: " +
215            theInventory.getVendorInventory());
216        System.out.println("\t\tPrice per unit:  " +
217            theInventory.getVendorPrice());
218        System.out.println("\t\tContact: ");
219
220        DatabaseEntry searchKey = null;
221        try {
222            searchKey =
223                new DatabaseEntry(theInventory.getVendor().getBytes("UTF-8"));
224        } catch (IOException willNeverOccur) {}
225        DatabaseEntry foundVendor = new DatabaseEntry();
226
227        if (myDbs.getVendorDB().get(null, searchKey, foundVendor,
228                LockMode.DEFAULT) != OperationStatus.SUCCESS) {
229            System.out.println("Could not find vendor: " +
230                theInventory.getVendor() + ".");
231            System.exit(-1);
232        } else {
233            Vendor theVendor =
234                (Vendor)vendorBinding.entryToObject(foundVendor);
235            System.out.println("\t\t " + theVendor.getAddress());
236            System.out.println("\t\t " + theVendor.getCity() + ", " +
237                theVendor.getState() + " " + theVendor.getZipcode());
238            System.out.println("\t\t Business Phone: " +
239                theVendor.getBusinessPhoneNumber());
240            System.out.println("\t\t Sales Rep: " +
241                                theVendor.getRepName());
242            System.out.println("\t\t            " +
243                theVendor.getRepPhoneNumber());
244       }
245    }</pre>
246        <p>The remainder of this application provides a utility method used
247      to parse the command line options. From the perspective of this
248      document, this is relatively uninteresting. You can see how this is
249      implemented by looking at:
250      </p>
251        <pre class="programlisting"><span class="emphasis"><em>DB_INSTALL</em></span>/examples_java/db/GettingStarted</pre>
252        <p>
253        where <tt class="literal"><span class="emphasis"><em>DB_INSTALL</em></span></tt> is the location where you
254        placed your DB distribution.
255    </p>
256      </div>
257    </div>
258    <div class="navfooter">
259      <hr />
260      <table width="100%" summary="Navigation footer">
261        <tr>
262          <td width="40%" align="left"><a accesskey="p" href="ReplacingEntryWCursor.html">Prev</a>��</td>
263          <td width="20%" align="center">
264            <a accesskey="u" href="Cursors.html">Up</a>
265          </td>
266          <td width="40%" align="right">��<a accesskey="n" href="indexes.html">Next</a></td>
267        </tr>
268        <tr>
269          <td width="40%" align="left" valign="top">Replacing Records Using Cursors��</td>
270          <td width="20%" align="center">
271            <a accesskey="h" href="index.html">Home</a>
272          </td>
273          <td width="40%" align="right" valign="top">��Chapter��10.��Secondary Databases</td>
274        </tr>
275      </table>
276    </div>
277  </body>
278</html>
279