KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > je > gettingStarted > ExampleDatabasePut


1 // file: ExampleDatabasePut.java
2
// $Id: ExampleDatabasePut.java,v 1.8 2006/05/01 17:42:32 sarette Exp $
3

4 package je.gettingStarted;
5
6 import java.io.BufferedReader JavaDoc;
7 import java.io.File JavaDoc;
8 import java.io.FileInputStream JavaDoc;
9 import java.io.FileNotFoundException JavaDoc;
10 import java.io.IOException JavaDoc;
11 import java.io.InputStreamReader JavaDoc;
12 import java.util.ArrayList JavaDoc;
13 import java.util.List JavaDoc;
14
15 import com.sleepycat.bind.EntryBinding;
16 import com.sleepycat.bind.serial.SerialBinding;
17 import com.sleepycat.bind.tuple.TupleBinding;
18 import com.sleepycat.je.DatabaseEntry;
19 import com.sleepycat.je.DatabaseException;
20 import com.sleepycat.je.Transaction;
21
22 public class ExampleDatabasePut {
23
24     private static File JavaDoc myDbEnvPath = new File JavaDoc("/tmp/JEDB");
25     private static File JavaDoc inventoryFile = new File JavaDoc("./inventory.txt");
26     private static File JavaDoc vendorsFile = new File JavaDoc("./vendors.txt");
27     
28     // DatabaseEntries used for loading records
29
private static DatabaseEntry theKey = new DatabaseEntry();
30     private static DatabaseEntry theData = new DatabaseEntry();
31     
32     // Encapsulates the environment and databases.
33
private static MyDbEnv myDbEnv = new MyDbEnv();
34     
35     private static void usage() {
36         System.out.println("ExampleDatabasePut [-h <env directory>]");
37         System.out.println(" [-s <selections file>] [-v <vendors file>]");
38         System.exit(-1);
39     }
40     
41
42     public static void main(String JavaDoc args[]) {
43         ExampleDatabasePut edp = new ExampleDatabasePut();
44         try {
45             edp.run(args);
46         } catch (DatabaseException dbe) {
47             System.err.println("ExampleDatabasePut: " + dbe.toString());
48             dbe.printStackTrace();
49             dbe.printStackTrace();
50         } catch (Exception JavaDoc e) {
51             System.out.println("Exception: " + e.toString());
52             e.printStackTrace();
53         } finally {
54             myDbEnv.close();
55         }
56         System.out.println("All done.");
57     }
58     
59     
60     private void run(String JavaDoc args[])
61         throws DatabaseException {
62         // Parse the arguments list
63
parseArgs(args);
64
65         myDbEnv.setup(myDbEnvPath, // path to the environment home
66
false); // is this environment read-only?
67

68         System.out.println("loading vendors db....");
69         loadVendorsDb();
70         
71         System.out.println("loading inventory db....");
72         loadInventoryDb();
73     }
74     
75     
76     private void loadVendorsDb()
77             throws DatabaseException {
78         
79         // loadFile opens a flat-text file that contains our data
80
// and loads it into a list for us to work with. The integer
81
// parameter represents the number of fields expected in the
82
// file.
83
List JavaDoc vendors = loadFile(vendorsFile, 8);
84         
85         // Now load the data into the database. The vendor's name is the
86
// key, and the data is a Vendor class object.
87

88         // Need a serial binding for the data
89
EntryBinding dataBinding =
90             new SerialBinding(myDbEnv.getClassCatalog(), Vendor.class);
91         
92         for (int i = 0; i < vendors.size(); i++) {
93             String JavaDoc[] sArray = (String JavaDoc[])vendors.get(i);
94             Vendor theVendor = new Vendor();
95             theVendor.setVendorName(sArray[0]);
96             theVendor.setAddress(sArray[1]);
97             theVendor.setCity(sArray[2]);
98             theVendor.setState(sArray[3]);
99             theVendor.setZipcode(sArray[4]);
100             theVendor.setBusinessPhoneNumber(sArray[5]);
101             theVendor.setRepName(sArray[6]);
102             theVendor.setRepPhoneNumber(sArray[7]);
103             
104             // The key is the vendor's name.
105
// ASSUMES THE VENDOR'S NAME IS UNIQUE!
106
String JavaDoc vendorName = theVendor.getVendorName();
107             try {
108                 theKey = new DatabaseEntry(vendorName.getBytes("UTF-8"));
109             } catch (IOException JavaDoc willNeverOccur) {}
110
111             // Convert the Vendor object to a DatabaseEntry object
112
// using our SerialBinding
113
dataBinding.objectToEntry(theVendor, theData);
114             
115             // Put it in the database. These puts are transactionally protected
116
// (we're using autocommit).
117
myDbEnv.getVendorDB().put(null, theKey, theData);
118         }
119     }
120     
121     private void loadInventoryDb()
122         throws DatabaseException {
123         
124         // loadFile opens a flat-text file that contains our data
125
// and loads it into a list for us to work with. The integer
126
// parameter represents the number of fields expected in the
127
// file.
128
List JavaDoc inventoryArray = loadFile(inventoryFile, 6);
129         
130         // Now load the data into the database. The item's sku is the
131
// key, and the data is an Inventory class object.
132

133         // Need a tuple binding for the Inventory class.
134
TupleBinding inventoryBinding = new InventoryBinding();
135         
136         // Start a transaction. All inventory items get loaded using a
137
// single transaction.
138
Transaction txn = myDbEnv.getEnv().beginTransaction(null, null);
139
140         for (int i = 0; i < inventoryArray.size(); i++) {
141             String JavaDoc[] sArray = (String JavaDoc[])inventoryArray.get(i);
142             String JavaDoc sku = sArray[1];
143             try {
144                 theKey = new DatabaseEntry(sku.getBytes("UTF-8"));
145             } catch (IOException JavaDoc willNeverOccur) {}
146             
147             Inventory theInventory = new Inventory();
148             theInventory.setItemName(sArray[0]);
149             theInventory.setSku(sArray[1]);
150             theInventory.setVendorPrice((new Float JavaDoc(sArray[2])).floatValue());
151             theInventory.setVendorInventory((new Integer JavaDoc(sArray[3])).intValue());
152             theInventory.setCategory(sArray[4]);
153             theInventory.setVendor(sArray[5]);
154
155             // Place the Vendor object on the DatabaseEntry object using our
156
// the tuple binding we implemented in InventoryBinding.java
157
inventoryBinding.objectToEntry(theInventory, theData);
158
159             // Put it in the database. Note that this causes our secondary database
160
// to be automatically updated for us.
161
try {
162                 myDbEnv.getInventoryDB().put(txn, theKey, theData);
163             } catch (DatabaseException dbe) {
164                 try {
165                 System.out.println("Error putting entry " +
166                                 sku.getBytes("UTF-8"));
167                 } catch (IOException JavaDoc willNeverOccur) {}
168                 txn.abort();
169                 throw dbe;
170             }
171         }
172         // Commit the transaction. The data is now safely written to the
173
// inventory database.
174
txn.commit();
175     }
176         
177
178     private static void parseArgs(String JavaDoc args[]) {
179         for(int i = 0; i < args.length; ++i) {
180             if (args[i].startsWith("-")) {
181                 switch(args[i].charAt(1)) {
182                   case 'h':
183                     myDbEnvPath = new File JavaDoc(args[++i]);
184                     break;
185                   case 'i':
186                     inventoryFile = new File JavaDoc(args[++i]);
187                     break;
188                   case 'v':
189                     vendorsFile = new File JavaDoc(args[++i]);
190                     break;
191                   default:
192                     usage();
193                 }
194             }
195         }
196     }
197
198     private List JavaDoc loadFile(File JavaDoc theFile, int numFields) {
199         List JavaDoc records = new ArrayList JavaDoc();
200         try {
201             String JavaDoc theLine = null;
202             FileInputStream JavaDoc fis = new FileInputStream JavaDoc(theFile);
203             BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(fis));
204             while((theLine=br.readLine()) != null) {
205                 String JavaDoc[] theLineArray = theLine.split("#");
206                 if (theLineArray.length != numFields) {
207                     System.out.println("Malformed line found in " + theFile.getPath());
208                     System.out.println("Line was: '" + theLine);
209                     System.out.println("length found was: " + theLineArray.length);
210                     System.exit(-1);
211                 }
212                 records.add(theLineArray);
213             }
214             // Close the input stream handle
215
fis.close();
216         } catch (FileNotFoundException JavaDoc e) {
217             System.err.println(theFile.getPath() + " does not exist.");
218             e.printStackTrace();
219             usage();
220         } catch (IOException JavaDoc e) {
221             System.err.println("IO Exception: " + e.toString());
222             e.printStackTrace();
223             System.exit(-1);
224         }
225         return records;
226     }
227
228     protected ExampleDatabasePut() {}
229 }
230
Popular Tags