KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > persist > gettingStarted > ExampleDatabasePut


1 package persist.gettingStarted;
2
3 import java.io.BufferedReader JavaDoc;
4 import java.io.File JavaDoc;
5 import java.io.FileInputStream JavaDoc;
6 import java.io.FileNotFoundException JavaDoc;
7 import java.io.IOException JavaDoc;
8 import java.io.InputStreamReader JavaDoc;
9 import java.util.ArrayList JavaDoc;
10 import java.util.List JavaDoc;
11
12 import com.sleepycat.je.DatabaseException;
13 import com.sleepycat.je.Transaction;
14
15 public class ExampleDatabasePut {
16
17     private static File JavaDoc myDbEnvPath = new File JavaDoc("/tmp/JEDB");
18     private static File JavaDoc inventoryFile = new File JavaDoc("./inventory.txt");
19     private static File JavaDoc vendorsFile = new File JavaDoc("./vendors.txt");
20
21     private DataAccessor da;
22     
23     // Encapsulates the environment and data store.
24
private static MyDbEnv myDbEnv = new MyDbEnv();
25     
26     private static void usage() {
27         System.out.println("ExampleDatabasePut [-h <env directory>]");
28         System.out.println(" [-i <inventory file>] [-v <vendors file>]");
29         System.exit(-1);
30     }
31     
32
33     public static void main(String JavaDoc args[]) {
34         ExampleDatabasePut edp = new ExampleDatabasePut();
35         try {
36             edp.run(args);
37         } catch (DatabaseException dbe) {
38             System.err.println("ExampleDatabasePut: " + dbe.toString());
39             dbe.printStackTrace();
40             dbe.printStackTrace();
41         } catch (Exception JavaDoc e) {
42             System.out.println("Exception: " + e.toString());
43             e.printStackTrace();
44         } finally {
45             myDbEnv.close();
46         }
47         System.out.println("All done.");
48     }
49     
50     
51     private void run(String JavaDoc args[])
52         throws DatabaseException {
53         // Parse the arguments list
54
parseArgs(args);
55
56         myDbEnv.setup(myDbEnvPath, // Path to the environment home
57
false); // Environment read-only?
58

59         // Open the data accessor. This is used to store
60
// persistent objects.
61
da = new DataAccessor(myDbEnv.getEntityStore());
62        
63         System.out.println("loading vendors db....");
64         loadVendorsDb();
65         
66         System.out.println("loading inventory db....");
67         loadInventoryDb();
68     }
69     
70     private void loadVendorsDb()
71             throws DatabaseException {
72         
73         // loadFile opens a flat-text file that contains our data
74
// and loads it into a list for us to work with. The integer
75
// parameter represents the number of fields expected in the
76
// file.
77
List JavaDoc vendors = loadFile(vendorsFile, 8);
78         
79         // Now load the data into the store.
80
for (int i = 0; i < vendors.size(); i++) {
81             String JavaDoc[] sArray = (String JavaDoc[])vendors.get(i);
82             Vendor theVendor = new Vendor();
83             theVendor.setVendorName(sArray[0]);
84             theVendor.setAddress(sArray[1]);
85             theVendor.setCity(sArray[2]);
86             theVendor.setState(sArray[3]);
87             theVendor.setZipcode(sArray[4]);
88             theVendor.setBusinessPhoneNumber(sArray[5]);
89             theVendor.setRepName(sArray[6]);
90             theVendor.setRepPhoneNumber(sArray[7]);
91             
92             // Put it in the store. Because we do not explicitly set
93
// a transaction here, and because the store was opened
94
// with transactional support, auto commit is used for each
95
// write to the store.
96
da.vendorByName.put(theVendor);
97         }
98     }
99     
100     private void loadInventoryDb()
101         throws DatabaseException {
102         
103         // loadFile opens a flat-text file that contains our data
104
// and loads it into a list for us to work with. The integer
105
// parameter represents the number of fields expected in the
106
// file.
107
List JavaDoc inventoryArray = loadFile(inventoryFile, 6);
108         
109         // Now load the data into the store. The item's sku is the
110
// key, and the data is an Inventory class object.
111

112         
113         // Start a transaction. All inventory items get loaded using a
114
// single transaction.
115
Transaction txn = myDbEnv.getEnv().beginTransaction(null, null);
116
117         for (int i = 0; i < inventoryArray.size(); i++) {
118             String JavaDoc[] sArray = (String JavaDoc[])inventoryArray.get(i);
119             String JavaDoc sku = sArray[1];
120             
121             Inventory theInventory = new Inventory();
122             theInventory.setItemName(sArray[0]);
123             theInventory.setSku(sArray[1]);
124             theInventory.setVendorPrice((new Float JavaDoc(sArray[2])).floatValue());
125             theInventory.setVendorInventory((new Integer JavaDoc(sArray[3])).intValue());
126             theInventory.setCategory(sArray[4]);
127             theInventory.setVendor(sArray[5]);
128
129             // Put it in the store. Note that this causes our secondary key
130
// to be automatically updated for us.
131
try {
132                   da.inventoryBySku.put(txn, theInventory);
133             } catch (DatabaseException dbe) {
134                 try {
135                 System.out.println("Error putting entry " +
136                                 sku.getBytes("UTF-8"));
137                 } catch (IOException JavaDoc willNeverOccur) {}
138                 txn.abort();
139                 throw dbe;
140             }
141         }
142         // Commit the transaction. The data is now safely written to the
143
// store.
144
txn.commit();
145     }
146         
147
148     private static void parseArgs(String JavaDoc args[]) {
149         for(int i = 0; i < args.length; ++i) {
150             if (args[i].startsWith("-")) {
151                 switch(args[i].charAt(1)) {
152                   case 'h':
153                     myDbEnvPath = new File JavaDoc(args[++i]);
154                     break;
155                   case 'i':
156                     inventoryFile = new File JavaDoc(args[++i]);
157                     break;
158                   case 'v':
159                     vendorsFile = new File JavaDoc(args[++i]);
160                     break;
161                   default:
162                     usage();
163                 }
164             }
165         }
166     }
167
168     private List JavaDoc loadFile(File JavaDoc theFile, int numFields) {
169         List JavaDoc<String JavaDoc[]> records = new ArrayList JavaDoc<String JavaDoc[]>();
170         try {
171             String JavaDoc theLine = null;
172             FileInputStream JavaDoc fis = new FileInputStream JavaDoc(theFile);
173             BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(fis));
174             while((theLine=br.readLine()) != null) {
175                 String JavaDoc[] theLineArray = theLine.split("#");
176                 if (theLineArray.length != numFields) {
177                     System.out.println("Malformed line found in " + theFile.getPath());
178                     System.out.println("Line was: '" + theLine);
179                     System.out.println("length found was: " + theLineArray.length);
180                     System.exit(-1);
181                 }
182                 records.add(theLineArray);
183             }
184             // Close the input stream handle
185
fis.close();
186         } catch (FileNotFoundException JavaDoc e) {
187             System.err.println(theFile.getPath() + " does not exist.");
188             e.printStackTrace();
189             usage();
190         } catch (IOException JavaDoc e) {
191             System.err.println("IO Exception: " + e.toString());
192             e.printStackTrace();
193             System.exit(-1);
194         }
195         return records;
196     }
197
198     protected ExampleDatabasePut() {}
199 }
200
Popular Tags