KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > je > SimpleExample


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

8
9 package je;
10
11 import java.io.File JavaDoc;
12
13 import com.sleepycat.bind.tuple.IntegerBinding;
14 import com.sleepycat.je.Cursor;
15 import com.sleepycat.je.Database;
16 import com.sleepycat.je.DatabaseConfig;
17 import com.sleepycat.je.DatabaseEntry;
18 import com.sleepycat.je.DatabaseException;
19 import com.sleepycat.je.Environment;
20 import com.sleepycat.je.EnvironmentConfig;
21 import com.sleepycat.je.LockMode;
22 import com.sleepycat.je.OperationStatus;
23 import com.sleepycat.je.Transaction;
24
25 /**
26  * SimpleExample creates a database environment, a database, and a database
27  * cursor, inserts and retrieves data.
28  */

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

51     public static void usage() {
52         System.out.println("usage: java " +
53                            "je.SimpleExample " +
54                            "<dbEnvHomeDirectory> " +
55                            "<insert|retrieve> <numRecords> [offset]");
56         System.exit(EXIT_FAILURE);
57     }
58
59     /**
60      * Main
61      */

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

112     public void run() throws DatabaseException {
113         /* Create a new, transactional database environment */
114         EnvironmentConfig envConfig = new EnvironmentConfig();
115         envConfig.setTransactional(true);
116         envConfig.setAllowCreate(true);
117         Environment exampleEnv = new Environment(envDir, envConfig);
118         
119         /*
120          * Make a database within that environment
121          *
122          * Notice that we use an explicit transaction to
123          * perform this database open, and that we
124          * immediately commit the transaction once the
125          * database is opened. This is required if we
126          * want transactional support for the database.
127          * However, we could have used autocommit to
128          * perform the same thing by simply passing a
129          * null txn handle to openDatabase().
130          */

131         Transaction txn = exampleEnv.beginTransaction(null, null);
132         DatabaseConfig dbConfig = new DatabaseConfig();
133         dbConfig.setTransactional(true);
134         dbConfig.setAllowCreate(true);
135         dbConfig.setSortedDuplicates(true);
136         Database exampleDb = exampleEnv.openDatabase(txn,
137                                                      "simpleDb",
138                                                      dbConfig);
139         txn.commit();
140
141         /*
142          * Insert or retrieve data. In our example, database records are
143          * integer pairs.
144          */

145
146         /* DatabaseEntry represents the key and data of each record */
147         DatabaseEntry keyEntry = new DatabaseEntry();
148         DatabaseEntry dataEntry = new DatabaseEntry();
149
150         if (doInsert) {
151
152             /* put some data in */
153             for (int i = offset; i < numRecords + offset; i++) {
154                 /*
155                  * Note that autocommit mode, described in the Getting
156                  * Started Guide, is an alternative to explicitly
157                  * creating the transaction object.
158                  */

159                 txn = exampleEnv.beginTransaction(null, null);
160
161                 /* Use a binding to convert the int into a DatabaseEntry. */
162
163                 IntegerBinding.intToEntry(i, keyEntry);
164                 IntegerBinding.intToEntry(i+1, dataEntry);
165                 OperationStatus status =
166                     exampleDb.put(txn, keyEntry, dataEntry);
167
168                 /*
169                  * Note that put will throw a DatabaseException when
170                  * error conditions are found such as deadlock.
171                  * However, the status return conveys a variety of
172                  * information. For example, the put might succeed,
173                  * or it might not succeed if the record alread exists
174                  * and the database was not configured for duplicate
175                  * records.
176                  */

177                 if (status != OperationStatus.SUCCESS) {
178                     throw new DatabaseException("Data insertion got status " +
179                                                 status);
180                 }
181                 txn.commit();
182             }
183         } else {
184             /* retrieve the data */
185             Cursor cursor = exampleDb.openCursor(null, null);
186
187             while (cursor.getNext(keyEntry, dataEntry, LockMode.DEFAULT) ==
188                    OperationStatus.SUCCESS) {
189                 System.out.println("key=" +
190                                    IntegerBinding.entryToInt(keyEntry) +
191                                    " data=" +
192                                    IntegerBinding.entryToInt(dataEntry));
193
194             }
195             cursor.close();
196         }
197
198         exampleDb.close();
199         exampleEnv.close();
200
201     }
202 }
203
Popular Tags