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