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>ExampleInventoryRead.class</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="dpl_example.html" title="Chapter 6. A DPL Example" />
11    <link rel="previous" href="dpl_exampledatabaseput.html" title="ExampleDatabasePut.class" />
12    <link rel="next" href="baseapi.html" title="Part II. Programming with the Base API" />
13  </head>
14  <body>
15    <div class="navheader">
16      <table width="100%" summary="Navigation header">
17        <tr>
18          <th colspan="3" align="center">ExampleInventoryRead.class</th>
19        </tr>
20        <tr>
21          <td width="20%" align="left"><a accesskey="p" href="dpl_exampledatabaseput.html">Prev</a> </td>
22          <th width="60%" align="center">Chapter 6. A DPL Example</th>
23          <td width="20%" align="right"> <a accesskey="n" href="baseapi.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="dpl_exampleinventoryread"></a>ExampleInventoryRead.class</h2>
33          </div>
34        </div>
35        <div></div>
36      </div>
37      <p>
38                    <tt class="classname">ExampleInventoryRead</tt>
39                    retrieves
40                    inventory information from our entity store and
41                    displays it. When it displays each inventory item, it
42                    also displays the related vendor contact information.
43            </p>
44      <p>
45                    <tt class="classname">ExampleInventoryRead</tt>
46                    can do one of two things. If you provide no search
47                    criteria, it displays all of the inventory items in the
48                    store. If you provide an item name (using the
49                    <tt class="literal">-s</tt> command line switch), then just
50                    those inventory items using that name are displayed.
51            </p>
52      <p>
53                    The beginning of our example is almost identical to our
54                    <tt class="classname">ExampleDatabasePut</tt>
55                    example program. We
56                    repeat that example code here for the sake of
57                    completeness. For a complete walk-through of it, see
58                    the previous section (<a href="dpl_exampledatabaseput.html">ExampleDatabasePut.class</a>).
59            </p>
60      <pre class="programlisting">package persist.gettingStarted;
61
62import java.io.File;
63import java.io.IOException;
64
65import com.sleepycat.db.DatabaseException;
66import com.sleepycat.persist.EntityCursor;
67
68public class ExampleInventoryRead {
69
70    private static File myDbEnvPath =
71        new File("/tmp/JEDB");
72
73    private DataAccessor da;
74
75    // Encapsulates the database environment.
76    private static MyDbEnv myDbEnv = new MyDbEnv();
77
78    // The item to locate if the -s switch is used
79    private static String locateItem;
80
81    private static void usage() {
82        System.out.println("ExampleInventoryRead [-h &lt;env directory&gt;]" +
83                           "[-s &lt;item to locate&gt;]");
84        System.exit(-1);
85    }
86
87    public static void main(String args[]) {
88        ExampleInventoryRead eir = new ExampleInventoryRead();
89        try {
90            eir.run(args);
91        } catch (DatabaseException dbe) {
92            System.err.println("ExampleInventoryRead: " + dbe.toString());
93            dbe.printStackTrace();
94        } finally {
95            myDbEnv.close();
96        }
97        System.out.println("All done.");
98    }
99
100    private void run(String args[])
101        throws DatabaseException {
102        // Parse the arguments list
103        parseArgs(args);
104
105        myDbEnv.setup(myDbEnvPath, // path to the environment home
106                      true);       // is this environment read-only?
107
108        // Open the data accessor. This is used to retrieve
109        // persistent objects.
110        da = new DataAccessor(myDbEnv.getEntityStore());
111
112        // If a item to locate is provided on the command line,
113        // show just the inventory items using the provided name.
114        // Otherwise, show everything in the inventory.
115        if (locateItem != null) {
116            showItem();
117        } else {
118            showAllInventory();
119        }
120    } </pre>
121      <p>
122            The first method that we provide is used to show inventory
123            items related to a given inventory name. This method is called
124            only if an inventory name is passed to
125            <tt class="classname">ExampleInventoryRead</tt>
126            via the <tt class="literal">-s</tt> option. Given the sample data
127            that we provide with this example, each matching inventory name
128            will result in the display of three inventory objects.
129    </p>
130      <p>
131            To display these objects we use the
132            <tt class="classname">Inventory</tt> class'
133            <tt class="literal">inventoryByName</tt> secondary index to retrieve
134            an <tt class="classname">EntityCursor</tt>, and then we iterate
135            over the resulting objects using the cursor.
136    </p>
137      <p>
138            Notice that this method calls
139            <tt class="methodname">displayInventoryRecord()</tt>
140            to display each individual object. We show this
141            method a little later in the example.
142    </p>
143      <pre class="programlisting">    // Shows all the inventory items that exist for a given
144    // inventory name.
145    private void showItem() throws DatabaseException {
146
147        // Use the inventory name secondary key to retrieve
148        // these objects.
149        EntityCursor&lt;Inventory&gt; items =
150            da.inventoryByName.subIndex(locateItem).entities();
151        try {
152            for (Inventory item : items) {
153                displayInventoryRecord(item);
154            }
155        } finally {
156            items.close();
157        }
158    } </pre>
159      <p>
160            Next we implement <tt class="methodname">showAllInventory()</tt>,
161            which shows all of the <tt class="classname">Inventory</tt>
162            objects in the store.  To do this, we
163            obtain an <tt class="classname">EntityCursor</tt>
164            from the <tt class="classname">Inventory</tt> class'
165            primary index and, again, we iterate using that cursor. 
166     </p>
167      <pre class="programlisting">    // Displays all the inventory items in the store
168    private void showAllInventory()
169        throws DatabaseException {
170
171        // Get a cursor that will walk every
172        // inventory object in the store.
173        EntityCursor&lt;Inventory&gt; items =
174            da.inventoryBySku.entities();
175
176        try {
177            for (Inventory item : items) {
178                displayInventoryRecord(item);
179            }
180        } finally {
181            items.close();
182        }
183    } </pre>
184      <p>
185                Now we implement
186                <tt class="methodname">displayInventoryRecord()</tt>. This
187                uses the getter methods on the <tt class="classname">Inventory</tt> 
188                class to obtain the information that we want to display.
189                The only thing interesting about this method is that we
190                obtain <tt class="classname">Vendor</tt> objects within.
191                The vendor objects are retrieved <tt class="classname">Vendor</tt> 
192                objects using their primary index. We get the key
193                for the retrieval from the <tt class="classname">Inventory</tt>
194                object that we are displaying at the time.
195            </p>
196      <pre class="programlisting">    private void displayInventoryRecord(Inventory theInventory)
197            throws DatabaseException {
198
199            System.out.println(theInventory.getSku() + ":");
200            System.out.println("\t " + theInventory.getItemName());
201            System.out.println("\t " + theInventory.getCategory());
202            System.out.println("\t " + theInventory.getVendor());
203            System.out.println("\t\tNumber in stock: " +
204                theInventory.getVendorInventory());
205            System.out.println("\t\tPrice per unit:  " +
206                theInventory.getVendorPrice());
207            System.out.println("\t\tContact: ");
208
209            Vendor theVendor =
210                    da.vendorByName.get(theInventory.getVendor());
211            assert theVendor != null;
212
213            System.out.println("\t\t " + theVendor.getAddress());
214            System.out.println("\t\t " + theVendor.getCity() + ", " +
215                theVendor.getState() + " " + theVendor.getZipcode());
216            System.out.println("\t\t Business Phone: " +
217                theVendor.getBusinessPhoneNumber());
218            System.out.println("\t\t Sales Rep: " +
219                                theVendor.getRepName());
220            System.out.println("\t\t            " +
221                theVendor.getRepPhoneNumber());
222    } </pre>
223      <p>
224                The last remaining parts of the example are used to parse
225                the command line. This is not very
226                interesting for our purposes here, but we show it anyway
227                for the sake of completeness.
228        </p>
229      <pre class="programlisting">    protected ExampleInventoryRead() {}
230
231    private static void parseArgs(String args[]) {
232        for(int i = 0; i &lt; args.length; ++i) {
233            if (args[i].startsWith("-")) {
234                switch(args[i].charAt(1)) {
235                    case 'h':
236                        myDbEnvPath = new File(args[++i]);
237                    break;
238                    case 's':
239                        locateItem = args[++i];
240                    break;
241                    default:
242                        usage();
243                }
244            }
245        }
246    }
247} </pre>
248    </div>
249    <div class="navfooter">
250      <hr />
251      <table width="100%" summary="Navigation footer">
252        <tr>
253          <td width="40%" align="left"><a accesskey="p" href="dpl_exampledatabaseput.html">Prev</a> </td>
254          <td width="20%" align="center">
255            <a accesskey="u" href="dpl_example.html">Up</a>
256          </td>
257          <td width="40%" align="right"> <a accesskey="n" href="baseapi.html">Next</a></td>
258        </tr>
259        <tr>
260          <td width="40%" align="left" valign="top">ExampleDatabasePut.class </td>
261          <td width="20%" align="center">
262            <a accesskey="h" href="index.html">Home</a>
263          </td>
264          <td width="40%" align="right" valign="top"> Part II. Programming with the Base API</td>
265        </tr>
266      </table>
267    </div>
268  </body>
269</html>
270