KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > je > BindingExample


1 /*-
2  * See the file LICENSE for redistribution information.
3  *
4  * Copyright (c) 2004,2006 Oracle. All rights reserved.
5  *
6  * $Id: BindingExample.java,v 1.17 2006/10/30 21:14:03 bostic Exp $
7  */

8
9 package je;
10
11 import java.io.File JavaDoc;
12 import java.io.Serializable JavaDoc;
13
14 import com.sleepycat.bind.EntryBinding;
15 import com.sleepycat.bind.serial.SerialBinding;
16 import com.sleepycat.bind.serial.StoredClassCatalog;
17 import com.sleepycat.bind.tuple.IntegerBinding;
18 import com.sleepycat.je.Cursor;
19 import com.sleepycat.je.Database;
20 import com.sleepycat.je.DatabaseConfig;
21 import com.sleepycat.je.DatabaseEntry;
22 import com.sleepycat.je.DatabaseException;
23 import com.sleepycat.je.Environment;
24 import com.sleepycat.je.EnvironmentConfig;
25 import com.sleepycat.je.LockMode;
26 import com.sleepycat.je.OperationStatus;
27 import com.sleepycat.je.Transaction;
28
29 /**
30  * BindingExample operates in the same way as SimpleExample, but uses a
31  * IntegerBinding and a SerialBinding to map between Java objects and stored
32  * DatabaseEntry objects.
33  */

34 class BindingExample {
35     private static final int EXIT_SUCCESS = 0;
36     private static final int EXIT_FAILURE = 1;
37
38     private int numRecords; // num records to insert or retrieve
39
private int offset; // where we want to start inserting
40
private boolean doInsert; // if true, insert, else retrieve
41
private File JavaDoc envDir;
42
43     public BindingExample(int numRecords,
44                           boolean doInsert,
45                           File JavaDoc envDir,
46                           int offset) {
47         this.numRecords = numRecords;
48         this.doInsert = doInsert;
49         this.envDir = envDir;
50         this.offset = offset;
51     }
52
53     /**
54      * Usage string
55      */

56     public static void usage() {
57         System.out.println("usage: java " +
58                            "je.BindingExample " +
59                            "<envHomeDirectory> " +
60                            "<insert|retrieve> <numRecords> [offset]");
61         System.exit(EXIT_FAILURE);
62     }
63
64     /**
65      * Main
66      */

67     public static void main(String JavaDoc argv[]) {
68
69         if (argv.length < 2) {
70             usage();
71             return;
72         }
73         File JavaDoc envHomeDirectory = new File JavaDoc(argv[0]);
74
75         boolean doInsertArg = false;
76         if (argv[1].equalsIgnoreCase("insert")) {
77             doInsertArg = true;
78         } else if (argv[1].equalsIgnoreCase("retrieve")) {
79             doInsertArg = false;
80         } else {
81             usage();
82         }
83
84         int startOffset = 0;
85         int numRecordsVal = 0;
86
87         if (doInsertArg) {
88
89             if (argv.length > 2) {
90                 numRecordsVal = Integer.parseInt(argv[2]);
91             } else {
92                 usage();
93                 return;
94             }
95
96             if (argv.length > 3) {
97                 startOffset = Integer.parseInt(argv[3]);
98             }
99         }
100
101         try {
102             BindingExample app = new BindingExample(numRecordsVal,
103                                                     doInsertArg,
104                                                     envHomeDirectory,
105                                                     startOffset);
106             app.run();
107         } catch (DatabaseException e) {
108             e.printStackTrace();
109             System.exit(EXIT_FAILURE);
110         }
111         System.exit(EXIT_SUCCESS);
112     }
113
114     /**
115      * Insert or retrieve data
116      */

117     public void run() throws DatabaseException {
118         /* Create a new, transactional database environment */
119         EnvironmentConfig envConfig = new EnvironmentConfig();
120         envConfig.setTransactional(true);
121         envConfig.setAllowCreate(true);
122         Environment exampleEnv = new Environment(envDir, envConfig);
123         
124         /* Make a database within that environment */
125         Transaction txn = exampleEnv.beginTransaction(null, null);
126         DatabaseConfig dbConfig = new DatabaseConfig();
127         dbConfig.setTransactional(true);
128         dbConfig.setAllowCreate(true);
129         dbConfig.setSortedDuplicates(true);
130         Database exampleDb = exampleEnv.openDatabase(txn,
131                                                      "bindingsDb",
132                                                      dbConfig);
133
134
135         /*
136          * In our example, the database record is composed of an integer
137          * key and and instance of the MyData class as data.
138          *
139          * A class catalog database is needed for storing class descriptions
140          * for the serial binding used below. This avoids storing class
141          * descriptions redundantly in each record.
142          */

143         DatabaseConfig catalogConfig = new DatabaseConfig();
144         catalogConfig.setTransactional(true);
145         catalogConfig.setAllowCreate(true);
146         Database catalogDb = exampleEnv.openDatabase(txn,
147                                                      "catalogDb",
148                                                      catalogConfig);
149         StoredClassCatalog catalog = new StoredClassCatalog(catalogDb);
150
151         /*
152          * Create a serial binding for MyData data objects. Serial bindings
153          * can be used to store any Serializable object.
154          */

155         EntryBinding dataBinding = new SerialBinding(catalog, MyData.class);
156         
157         txn.commit();
158
159         /*
160          * Further below we'll use a tuple binding (IntegerBinding
161          * specifically) for integer keys. Tuples, unlike serialized Java
162          * objects, have a well defined sort order.
163          */

164
165         /* DatabaseEntry represents the key and data of each record */
166         DatabaseEntry keyEntry = new DatabaseEntry();
167         DatabaseEntry dataEntry = new DatabaseEntry();
168
169         if (doInsert) {
170
171             /* put some data in */
172             for (int i = offset; i < numRecords + offset; i++) {
173
174                 StringBuffer JavaDoc stars = new StringBuffer JavaDoc();
175                 for (int j = 0; j < i; j++) {
176                     stars.append('*');
177                 }
178                 MyData data = new MyData(i, stars.toString());
179
180                 IntegerBinding.intToEntry(i, keyEntry);
181                 dataBinding.objectToEntry(data, dataEntry);
182
183                 txn = exampleEnv.beginTransaction(null, null);
184                 OperationStatus status =
185                     exampleDb.put(txn, keyEntry, dataEntry);
186
187                 /*
188                  * Note that put will throw a DatabaseException when
189                  * error conditions are found such as deadlock.
190                  * However, the status return conveys a variety of
191                  * information. For example, the put might succeed,
192                  * or it might not succeed if the record exists
193                  * and duplicates were not
194                  */

195                 if (status != OperationStatus.SUCCESS) {
196                     throw new DatabaseException("Data insertion got status " +
197                                                 status);
198                 }
199                 txn.commit();
200             }
201         } else {
202
203             /* retrieve the data */
204             Cursor cursor = exampleDb.openCursor(null, null);
205
206             while (cursor.getNext(keyEntry, dataEntry, LockMode.DEFAULT) ==
207                    OperationStatus.SUCCESS) {
208
209                 int key = IntegerBinding.entryToInt(keyEntry);
210                 MyData data = (MyData) dataBinding.entryToObject(dataEntry);
211
212                 System.out.println("key=" + key + " data=" + data);
213             }
214             cursor.close();
215         }
216
217         catalogDb.close();
218         exampleDb.close();
219         exampleEnv.close();
220     }
221
222     private static class MyData implements Serializable JavaDoc {
223
224         private int num;
225         private String JavaDoc msg;
226
227         MyData(int number, String JavaDoc message) {
228             this.num = number;
229             this.msg = message;
230         }
231
232         public String JavaDoc toString() {
233             return String.valueOf(num) + ' ' + msg;
234         }
235     }
236 }
237
Popular Tags