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>ExampleDatabasePut.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="dataaccessorclass.html" title="DataAccessor.class" />
12    <link rel="next" href="dpl_exampleinventoryread.html" title="ExampleInventoryRead.class" />
13  </head>
14  <body>
15    <div class="navheader">
16      <table width="100%" summary="Navigation header">
17        <tr>
18          <th colspan="3" align="center">ExampleDatabasePut.class</th>
19        </tr>
20        <tr>
21          <td width="20%" align="left"><a accesskey="p" href="dataaccessorclass.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="dpl_exampleinventoryread.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_exampledatabaseput"></a>ExampleDatabasePut.class</h2>
33          </div>
34        </div>
35        <div></div>
36      </div>
37      <p>
38                   Our example reads inventory and vendor information from
39                   flat text files, encapsulates this data in objects of
40                   the appropriate type, and then writes each object to an
41                   <tt class="classname">EntityStore</tt>.
42           </p>
43      <p>
44                To begin, we import the Java classes that our example
45                needs. Most of the imports are related to reading the raw
46                data from flat text files and breaking them apart for usage
47                with our data classes. We also import classes from the
48                DB package, but we do not actually import any classes
49                from the DPL. The reason why is because we have
50                placed almost all of our DPL work off into
51                other classes, so there is no need for direct usage of
52                those APIs here.
53           </p>
54      <pre class="programlisting">package persist.gettingStarted;
55
56import java.io.BufferedReader;
57import java.io.File;
58import java.io.FileInputStream;
59import java.io.FileNotFoundException;
60import java.io.IOException;
61import java.io.InputStreamReader;
62import java.util.ArrayList;
63import java.util.List;
64
65import com.sleepycat.db.DatabaseException; </pre>
66      <p>
67            Now we can begin the class itself. Here we set default paths
68            for the on-disk resources that we require (the environment
69            home, and the location of the text files containing our sample
70            data). We also declare <tt class="classname">DataAccessor</tt>
71            and <tt class="classname">MyDbEnv</tt> members. We describe these
72            classes and show their implementation in
73            <a href="dataaccessorclass.html">DataAccessor.class</a>
74            and
75            <a href="mydbenv-persist.html">MyDbEnv</a>.
76        </p>
77      <pre class="programlisting">public class ExampleDatabasePut {
78
79    private static File myDbEnvPath = new File("/tmp/JEDB");
80    private static File inventoryFile = new File("/inventory.txt");
81    private static File vendorsFile = new File("/vendors.txt");
82
83    private DataAccessor da;
84
85    // Encapsulates the environment and data store.
86    private static MyDbEnv myDbEnv = new MyDbEnv();</pre>
87      <p>
88            Next, we provide our <tt class="methodname">usage()</tt>
89            method. The command line options provided there are necessary
90            only if the default values to the on-disk resources are not
91            sufficient.
92    </p>
93      <pre class="programlisting">    private static void usage() {
94        System.out.println("ExampleDatabasePut [-h &lt;env directory&gt;]");
95        System.out.println("      [-i &lt;inventory file&gt;] [-v &lt;vendors file&gt;]");
96        System.exit(-1);
97    } </pre>
98      <p>
99        Our <tt class="methodname">main()</tt> method is also reasonably
100        self-explanatory. We simply instantiate an
101        <tt class="classname">ExampleDatabasePut</tt> object there and then
102        call its <tt class="methodname">run()</tt> method. We also provide a
103        top-level <tt class="literal">try</tt> block there for any exceptions that might be thrown
104        during runtime.
105    </p>
106      <p>
107        Notice that the <tt class="literal">finally</tt> statement in the
108        top-level <tt class="literal">try</tt> block calls
109        <tt class="methodname">MyDbEnv.close()</tt>. This method closes our
110        <tt class="classname">EntityStore</tt> and <tt class="classname">Environment</tt>
111        objects. By placing it here in the <tt class="literal">finally</tt>
112        statement, we can make sure that our store and environment are
113        always cleanly closed.
114    </p>
115      <pre class="programlisting">    public static void main(String args[]) {
116        ExampleDatabasePut edp = new ExampleDatabasePut();
117        try {
118            edp.run(args);
119        } catch (DatabaseException dbe) {
120            System.err.println("ExampleDatabasePut: " + dbe.toString());
121            dbe.printStackTrace();
122        } catch (Exception e) {
123            System.out.println("Exception: " + e.toString());
124            e.printStackTrace();
125        } finally {
126            myDbEnv.close();
127        }
128        System.out.println("All done.");
129    } </pre>
130      <p>
131               Our <tt class="methodname">run()</tt> method does four
132            things. It calls <tt class="methodname">MyDbEnv.setup()</tt>,
133            which opens our <tt class="classname">Environment</tt> and
134            <tt class="classname">EntityStore</tt>.  It then instantiates a
135            <tt class="classname">DataAccessor</tt> object, which we will use
136            to write data to the store.  It calls
137            <tt class="methodname">loadVendorsDb()</tt> which loads all of the
138            vendor information. And then it calls
139            <tt class="methodname">loadInventoryDb()</tt> which loads all of
140            the inventory information.
141       </p>
142      <p>
143            Notice that the <tt class="classname">MyDbEnv</tt>
144            object is being setup as read-write. This results in the
145            <tt class="classname">EntityStore</tt> being opened for
146            transactional support. 
147            (See <a href="mydbenv-persist.html">MyDbEnv</a>
148            for implementation details.)
149        </p>
150      <pre class="programlisting">    private void run(String args[])
151        throws DatabaseException {
152        // Parse the arguments list
153        parseArgs(args);
154
155        myDbEnv.setup(myDbEnvPath,  // Path to the environment home 
156                      false);       // Environment read-only?
157
158        // Open the data accessor. This is used to store
159        // persistent objects.
160        da = new DataAccessor(myDbEnv.getEntityStore());
161
162        System.out.println("loading vendors db....");
163        loadVendorsDb();
164
165        System.out.println("loading inventory db....");
166        loadInventoryDb();
167    } </pre>
168      <p>
169            We can now implement the <tt class="methodname">loadVendorsDb()</tt>
170            method. This method is responsible for reading the vendor
171            contact information from the appropriate flat-text file,
172            populating <tt class="classname">Vendor</tt> class objects with the
173            data and then writing it to the <tt class="classname">EntityStore</tt>.
174            As explained above, each individual object is written with
175            transactional support. However, because a transaction handle is
176            not explicitly used, the write is performed using auto-commit.
177            This happens because the <tt class="classname">EntityStore</tt>
178            was opened to support transactions.
179    </p>
180      <p>
181            To actually write each class to the
182            <tt class="classname">EntityStore</tt>, we simply call the
183            <tt class="methodname">PrimaryIndex.put()</tt> method for the
184            <tt class="classname">Vendor</tt> entity instance. We obtain this
185            method from our <tt class="classname">DataAccessor</tt>
186            class.
187    </p>
188      <pre class="programlisting">    private void loadVendorsDb()
189            throws DatabaseException {
190
191        // loadFile opens a flat-text file that contains our data
192        // and loads it into a list for us to work with. The integer
193        // parameter represents the number of fields expected in the
194        // file.
195        List vendors = loadFile(vendorsFile, 8);
196
197        // Now load the data into the store.
198        for (int i = 0; i &lt; vendors.size(); i++) {
199            String[] sArray = (String[])vendors.get(i);
200            Vendor theVendor = new Vendor();
201            theVendor.setVendorName(sArray[0]);
202            theVendor.setAddress(sArray[1]);
203            theVendor.setCity(sArray[2]);
204            theVendor.setState(sArray[3]);
205            theVendor.setZipcode(sArray[4]);
206            theVendor.setBusinessPhoneNumber(sArray[5]);
207            theVendor.setRepName(sArray[6]);
208            theVendor.setRepPhoneNumber(sArray[7]);
209
210            // Put it in the store.
211            da.vendorByName.put(theVendor);
212        }
213    } </pre>
214      <p>
215            Now we can implement our <tt class="methodname">loadInventoryDb()</tt>
216            method. This does exactly the same thing as the
217            <tt class="methodname">loadVendorsDb()</tt>
218            method.
219    </p>
220      <pre class="programlisting">    private void loadInventoryDb()
221        throws DatabaseException {
222
223        // loadFile opens a flat-text file that contains our data
224        // and loads it into a list for us to work with. The integer
225        // parameter represents the number of fields expected in the
226        // file.
227        List inventoryArray = loadFile(inventoryFile, 6);
228
229        // Now load the data into the store. The item's sku is the
230        // key, and the data is an Inventory class object.
231
232        for (int i = 0; i &lt; inventoryArray.size(); i++) {
233            String[] sArray = (String[])inventoryArray.get(i);
234            String sku = sArray[1];
235
236            Inventory theInventory = new Inventory();
237            theInventory.setItemName(sArray[0]);
238            theInventory.setSku(sArray[1]);
239            theInventory.setVendorPrice(
240                (new Float(sArray[2])).floatValue());
241            theInventory.setVendorInventory(
242                (new Integer(sArray[3])).intValue());
243            theInventory.setCategory(sArray[4]);
244            theInventory.setVendor(sArray[5]);
245
246            // Put it in the store. Note that this causes our secondary key
247            // to be automatically updated for us.
248            da.inventoryBySku.put(theInventory);
249        }
250    } </pre>
251      <p>
252            The remainder of this example simple parses the command line
253            and loads data from a flat-text file. There is nothing here
254            that is of specific interest to the DPL, but we
255            show this part of the example anyway in the interest of
256            completeness.
257    </p>
258      <pre class="programlisting">    private static void parseArgs(String args[]) {
259        for(int i = 0; i &lt; args.length; ++i) {
260            if (args[i].startsWith("-")) {
261                switch(args[i].charAt(1)) {
262                  case 'h':
263                    myDbEnvPath = new File(args[++i]);
264                    break;
265                  case 'i':
266                    inventoryFile = new File(args[++i]);
267                    break;
268                  case 'v':
269                    vendorsFile = new File(args[++i]);
270                    break;
271                  default:
272                    usage();
273                }
274            }
275        }
276    }
277
278    private List loadFile(File theFile, int numFields) {
279        List&lt;String[]&gt; records = new ArrayList&lt;String[]&gt;();
280        try {
281            String theLine = null;
282            FileInputStream fis = new FileInputStream(theFile);
283            BufferedReader br = 
284                new BufferedReader(new InputStreamReader(fis));
285            while((theLine=br.readLine()) != null) {
286                String[] theLineArray = theLine.split("#");
287                if (theLineArray.length != numFields) {
288                    System.out.println("Malformed line found in " + 
289                        theFile.getPath());
290                    System.out.println("Line was: '" + theLine);
291                    System.out.println("length found was: " + 
292                        theLineArray.length);
293                    System.exit(-1);
294                }
295                records.add(theLineArray);
296            }
297            // Close the input stream handle
298            fis.close();
299        } catch (FileNotFoundException e) {
300            System.err.println(theFile.getPath() + " does not exist.");
301            e.printStackTrace();
302            usage();
303        } catch (IOException e)  {
304            System.err.println("IO Exception: " + e.toString());
305            e.printStackTrace();
306            System.exit(-1);
307        }
308        return records;
309    }
310
311    protected ExampleDatabasePut() {}
312} </pre>
313    </div>
314    <div class="navfooter">
315      <hr />
316      <table width="100%" summary="Navigation footer">
317        <tr>
318          <td width="40%" align="left"><a accesskey="p" href="dataaccessorclass.html">Prev</a> </td>
319          <td width="20%" align="center">
320            <a accesskey="u" href="dpl_example.html">Up</a>
321          </td>
322          <td width="40%" align="right"> <a accesskey="n" href="dpl_exampleinventoryread.html">Next</a></td>
323        </tr>
324        <tr>
325          <td width="40%" align="left" valign="top">DataAccessor.class </td>
326          <td width="20%" align="center">
327            <a accesskey="h" href="index.html">Home</a>
328          </td>
329          <td width="40%" align="right" valign="top"ExampleInventoryRead.class</td>
330        </tr>
331      </table>
332    </div>
333  </body>
334</html>
335