File: dpl_exampledatabaseput.html

package info (click to toggle)
db5.3 5.3.28%2Bdfsg1-0.8
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 158,400 kB
  • sloc: ansic: 448,406; java: 111,824; tcl: 80,544; sh: 44,326; cs: 33,697; cpp: 21,604; perl: 14,557; xml: 10,799; makefile: 4,077; javascript: 1,998; yacc: 1,003; awk: 965; sql: 801; erlang: 342; python: 216; php: 24; asm: 14
file content (337 lines) | stat: -rw-r--r-- 14,872 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>ExampleDatabasePut.java</title>
    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
    <link rel="start" href="index.html" title="Getting Started with Berkeley DB" />
    <link rel="up" href="dpl_example.html" title="Chapter 6. A DPL Example" />
    <link rel="prev" href="dataaccessorclass.html" title="DataAccessor.java" />
    <link rel="next" href="dpl_exampleinventoryread.html" title="ExampleInventoryRead.java" />
  </head>
  <body>
    <div xmlns="" class="navheader">
      <div class="libver">
        <p>Library Version 11.2.5.3</p>
      </div>
      <table width="100%" summary="Navigation header">
        <tr>
          <th colspan="3" align="center">ExampleDatabasePut.java</th>
        </tr>
        <tr>
          <td width="20%" align="left"><a accesskey="p" href="dataaccessorclass.html">Prev</a> </td>
          <th width="60%" align="center">Chapter 6. A DPL Example</th>
          <td width="20%" align="right"> <a accesskey="n" href="dpl_exampleinventoryread.html">Next</a></td>
        </tr>
      </table>
      <hr />
    </div>
    <div class="sect1" lang="en" xml:lang="en">
      <div class="titlepage">
        <div>
          <div>
            <h2 class="title" style="clear: both"><a id="dpl_exampledatabaseput"></a>ExampleDatabasePut.java</h2>
          </div>
        </div>
      </div>
      <p>
                   Our example reads inventory and vendor information from
                   flat text files, encapsulates this data in objects of
                   the appropriate type, and then writes each object to an
                   <code class="classname">EntityStore</code>.
           </p>
      <p>
                To begin, we import the Java classes that our example
                needs. Most of the imports are related to reading the raw
                data from flat text files and breaking them apart for usage
                with our data classes. We also import classes from the
                DB package, but we do not actually import any classes
                from the DPL. The reason why is because we have
                placed almost all of our DPL work off into
                other classes, so there is no need for direct usage of
                those APIs here.
           </p>
      <pre class="programlisting">package persist.gettingStarted;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import com.sleepycat.db.DatabaseException; </pre>
      <p>
            Now we can begin the class itself. Here we set default paths
            for the on-disk resources that we require (the environment
            home, and the location of the text files containing our sample
            data). We also declare <code class="classname">DataAccessor</code>
            and <code class="classname">MyDbEnv</code> members. We describe these
            classes and show their implementation in
            <a class="xref" href="dataaccessorclass.html" title="DataAccessor.java">DataAccessor.java</a>
            and
            <a class="xref" href="mydbenv-persist.html" title="MyDbEnv">MyDbEnv</a>.
        </p>
      <pre class="programlisting">public class ExampleDatabasePut {

    private static File myDbEnvPath = new File("/tmp/JEDB");
    private static File inventoryFile = new File("./inventory.txt");
    private static File vendorsFile = new File("./vendors.txt");

    private DataAccessor da;

    // Encapsulates the environment and data store.
    private static MyDbEnv myDbEnv = new MyDbEnv();</pre>
      <p>
            Next, we provide our <code class="methodname">usage()</code>
            method. The command line options provided there are necessary
            only if the default values to the on-disk resources are not
            sufficient.
    </p>
      <pre class="programlisting">    private static void usage() {
        System.out.println("ExampleDatabasePut [-h &lt;env directory&gt;]");
        System.out.println("      [-i &lt;inventory file&gt;]");
        System.out.println("      [-v &lt;vendors file&gt;]");
        System.exit(-1);
    } </pre>
      <p>
        Our <code class="methodname">main()</code> method is also reasonably
        self-explanatory. We simply instantiate an
        <code class="classname">ExampleDatabasePut</code> object there and then
        call its <code class="methodname">run()</code> method. We also provide a
        top-level <code class="literal">try</code> block there for any exceptions that might be thrown
        during runtime.
    </p>
      <p>
        Notice that the <code class="literal">finally</code> statement in the
        top-level <code class="literal">try</code> block calls
        <code class="methodname">MyDbEnv.close()</code>. This method closes our
        <code class="classname">EntityStore</code> and <code class="classname">Environment</code>
        objects. By placing it here in the <code class="literal">finally</code>
        statement, we can make sure that our store and environment are
        always cleanly closed.
    </p>
      <pre class="programlisting">    public static void main(String args[]) {
        ExampleDatabasePut edp = new ExampleDatabasePut();
        try {
            edp.run(args);
        } catch (DatabaseException dbe) {
            System.err.println("ExampleDatabasePut: " + dbe.toString());
            dbe.printStackTrace();
        } catch (Exception e) {
            System.out.println("Exception: " + e.toString());
            e.printStackTrace();
        } finally {
            myDbEnv.close();
        }
        System.out.println("All done.");
    } </pre>
      <p>
               Our <code class="methodname">run()</code> method does four
            things. It calls <code class="methodname">MyDbEnv.setup()</code>,
            which opens our <code class="classname">Environment</code> and
            <code class="classname">EntityStore</code>.  It then instantiates a
            <code class="classname">DataAccessor</code> object, which we will use
            to write data to the store.  It calls
            <code class="methodname">loadVendorsDb()</code> which loads all of the
            vendor information. And then it calls
            <code class="methodname">loadInventoryDb()</code> which loads all of
            the inventory information.
       </p>
      <p>
            Notice that the <code class="classname">MyDbEnv</code>
            object is being setup as read-write. This results in the
            <code class="classname">EntityStore</code> being opened for
            transactional support. 
            (See <a class="xref" href="mydbenv-persist.html" title="MyDbEnv">MyDbEnv</a>
            for implementation details.)
        </p>
      <pre class="programlisting">    private void run(String args[])
        throws DatabaseException {
        // Parse the arguments list
        parseArgs(args);

        myDbEnv.setup(myDbEnvPath,  // Path to the environment home 
                      false);       // Environment read-only?

        // Open the data accessor. This is used to store
        // persistent objects.
        da = new DataAccessor(myDbEnv.getEntityStore());

        System.out.println("loading vendors db....");
        loadVendorsDb();

        System.out.println("loading inventory db....");
        loadInventoryDb();
    } </pre>
      <p>
            We can now implement the <code class="methodname">loadVendorsDb()</code>
            method. This method is responsible for reading the vendor
            contact information from the appropriate flat-text file,
            populating <code class="classname">Vendor</code> class objects with the
            data and then writing it to the <code class="classname">EntityStore</code>.
            As explained above, each individual object is written with
            transactional support. However, because a transaction handle is
            not explicitly used, the write is performed using auto-commit.
            This happens because the <code class="classname">EntityStore</code>
            was opened to support transactions.
    </p>
      <p>
            To actually write each class to the
            <code class="classname">EntityStore</code>, we simply call the
            <code class="methodname">PrimaryIndex.put()</code> method for the
            <code class="classname">Vendor</code> entity instance. We obtain this
            method from our <code class="classname">DataAccessor</code>
            class.
    </p>
      <pre class="programlisting">    private void loadVendorsDb()
            throws DatabaseException {

        // loadFile opens a flat-text file that contains our data
        // and loads it into a list for us to work with. The integer
        // parameter represents the number of fields expected in the
        // file.
        List vendors = loadFile(vendorsFile, 8);

        // Now load the data into the store.
        for (int i = 0; i &lt; vendors.size(); i++) {
            String[] sArray = (String[])vendors.get(i);
            Vendor theVendor = new Vendor();
            theVendor.setVendorName(sArray[0]);
            theVendor.setAddress(sArray[1]);
            theVendor.setCity(sArray[2]);
            theVendor.setState(sArray[3]);
            theVendor.setZipcode(sArray[4]);
            theVendor.setBusinessPhoneNumber(sArray[5]);
            theVendor.setRepName(sArray[6]);
            theVendor.setRepPhoneNumber(sArray[7]);

            // Put it in the store.
            da.vendorByName.put(theVendor);
        }
    } </pre>
      <p>
            Now we can implement our <code class="methodname">loadInventoryDb()</code>
            method. This does exactly the same thing as the
            <code class="methodname">loadVendorsDb()</code>
            method.
    </p>
      <pre class="programlisting">    private void loadInventoryDb()
        throws DatabaseException {

        // loadFile opens a flat-text file that contains our data
        // and loads it into a list for us to work with. The integer
        // parameter represents the number of fields expected in the
        // file.
        List inventoryArray = loadFile(inventoryFile, 6);

        // Now load the data into the store. The item's sku is the
        // key, and the data is an Inventory class object.

        for (int i = 0; i &lt; inventoryArray.size(); i++) {
            String[] sArray = (String[])inventoryArray.get(i);
            String sku = sArray[1];

            Inventory theInventory = new Inventory();
            theInventory.setItemName(sArray[0]);
            theInventory.setSku(sArray[1]);
            theInventory.setVendorPrice(
                (new Float(sArray[2])).floatValue());
            theInventory.setVendorInventory(
                (new Integer(sArray[3])).intValue());
            theInventory.setCategory(sArray[4]);
            theInventory.setVendor(sArray[5]);

            // Put it in the store. Note that this causes our secondary key
            // to be automatically updated for us.
            da.inventoryBySku.put(theInventory);
        }
    } </pre>
      <p>
            The remainder of this example simple parses the command line
            and loads data from a flat-text file. There is nothing here
            that is of specific interest to the DPL, but we
            show this part of the example anyway in the interest of
            completeness.
    </p>
      <pre class="programlisting">    private static void parseArgs(String args[]) {
        for(int i = 0; i &lt; args.length; ++i) {
            if (args[i].startsWith("-")) {
                switch(args[i].charAt(1)) {
                  case 'h':
                    myDbEnvPath = new File(args[++i]);
                    break;
                  case 'i':
                    inventoryFile = new File(args[++i]);
                    break;
                  case 'v':
                    vendorsFile = new File(args[++i]);
                    break;
                  default:
                    usage();
                }
            }
        }
    }

    private List loadFile(File theFile, int numFields) {
        List&lt;String[]&gt; records = new ArrayList&lt;String[]&gt;();
        try {
            String theLine = null;
            FileInputStream fis = new FileInputStream(theFile);
            BufferedReader br = 
                new BufferedReader(new InputStreamReader(fis));
            while((theLine=br.readLine()) != null) {
                String[] theLineArray = theLine.split("#");
                if (theLineArray.length != numFields) {
                    System.out.println("Malformed line found in " + 
                        theFile.getPath());
                    System.out.println("Line was: '" + theLine);
                    System.out.println("length found was: " + 
                        theLineArray.length);
                    System.exit(-1);
                }
                records.add(theLineArray);
            }
            // Close the input stream handle
            fis.close();
        } catch (FileNotFoundException e) {
            System.err.println(theFile.getPath() + " does not exist.");
            e.printStackTrace();
            usage();
        } catch (IOException e)  {
            System.err.println("IO Exception: " + e.toString());
            e.printStackTrace();
            System.exit(-1);
        }
        return records;
    }

    protected ExampleDatabasePut() {}
} </pre>
    </div>
    <div class="navfooter">
      <hr />
      <table width="100%" summary="Navigation footer">
        <tr>
          <td width="40%" align="left"><a accesskey="p" href="dataaccessorclass.html">Prev</a> </td>
          <td width="20%" align="center">
            <a accesskey="u" href="dpl_example.html">Up</a>
          </td>
          <td width="40%" align="right"> <a accesskey="n" href="dpl_exampleinventoryread.html">Next</a></td>
        </tr>
        <tr>
          <td width="40%" align="left" valign="top">DataAccessor.java </td>
          <td width="20%" align="center">
            <a accesskey="h" href="index.html">Home</a>
          </td>
          <td width="40%" align="right" valign="top"> ExampleInventoryRead.java</td>
        </tr>
      </table>
    </div>
  </body>
</html>