1 /*-
2  * See the file LICENSE for redistribution information.
3  *
4  * Copyright (c) 2004, 2010 Oracle and/or its affiliates.  All rights reserved.
5  *
6  */
7 
8 package je;
9 
10 import java.io.File;
11 
12 import com.sleepycat.bind.tuple.IntegerBinding;
13 import com.sleepycat.je.Cursor;
14 import com.sleepycat.je.Database;
15 import com.sleepycat.je.DatabaseConfig;
16 import com.sleepycat.je.DatabaseEntry;
17 import com.sleepycat.je.DatabaseException;
18 import com.sleepycat.je.Environment;
19 import com.sleepycat.je.EnvironmentConfig;
20 import com.sleepycat.je.LockMode;
21 import com.sleepycat.je.OperationStatus;
22 import com.sleepycat.je.Transaction;
23 
24 /**
25  * SimpleExample creates a database environment, a database, and a database
26  * cursor, inserts and retrieves data.
27  */
28 class SimpleExample {
29     private static final int EXIT_SUCCESS = 0;
30     private static final int EXIT_FAILURE = 1;
31 
32     private int numRecords;   // num records to insert or retrieve
33     private int offset;       // where we want to start inserting
34     private boolean doInsert; // if true, insert, else retrieve
35     private File envDir;
36 
SimpleExample(int numRecords, boolean doInsert, File envDir, int offset)37     public SimpleExample(int numRecords,
38                          boolean doInsert,
39                          File envDir,
40                          int offset) {
41         this.numRecords = numRecords;
42         this.doInsert = doInsert;
43         this.envDir = envDir;
44         this.offset = offset;
45     }
46 
47     /**
48      * Usage string
49      */
usage()50     public static void usage() {
51         System.out.println("usage: java " +
52                            "je.SimpleExample " +
53                            "<dbEnvHomeDirectory> " +
54                            "<insert|retrieve> <numRecords> [offset]");
55         System.exit(EXIT_FAILURE);
56     }
57 
58     /**
59      * Main
60      */
main(String argv[])61     public static void main(String argv[]) {
62 
63         if (argv.length < 2) {
64             usage();
65             return;
66         }
67         File envHomeDirectory = new File(argv[0]);
68 
69         boolean doInsertArg = false;
70         if (argv[1].equalsIgnoreCase("insert")) {
71             doInsertArg = true;
72         } else if (argv[1].equalsIgnoreCase("retrieve")) {
73             doInsertArg = false;
74         } else {
75             usage();
76         }
77 
78         int startOffset = 0;
79         int numRecordsVal = 0;
80 
81         if (doInsertArg) {
82 
83             if (argv.length > 2) {
84                 numRecordsVal = Integer.parseInt(argv[2]);
85             } else {
86                 usage();
87                 return;
88             }
89 
90             if (argv.length > 3) {
91                 startOffset = Integer.parseInt(argv[3]);
92             }
93         }
94 
95         try {
96             SimpleExample app = new SimpleExample(numRecordsVal,
97                                                   doInsertArg,
98                                                   envHomeDirectory,
99                                                   startOffset);
100             app.run();
101         } catch (DatabaseException e) {
102             e.printStackTrace();
103             System.exit(EXIT_FAILURE);
104         }
105         System.exit(EXIT_SUCCESS);
106     }
107 
108     /**
109      * Insert or retrieve data
110      */
run()111     public void run() throws DatabaseException {
112         /* Create a new, transactional database environment */
113         EnvironmentConfig envConfig = new EnvironmentConfig();
114         envConfig.setTransactional(true);
115         envConfig.setAllowCreate(true);
116         Environment exampleEnv = new Environment(envDir, envConfig);
117 
118         /*
119          * Make a database within that environment
120          *
121          * Notice that we use an explicit transaction to
122          * perform this database open, and that we
123          * immediately commit the transaction once the
124          * database is opened. This is required if we
125          * want transactional support for the database.
126          * However, we could have used autocommit to
127          * perform the same thing by simply passing a
128          * null txn handle to openDatabase().
129          */
130         Transaction txn = exampleEnv.beginTransaction(null, null);
131         DatabaseConfig dbConfig = new DatabaseConfig();
132         dbConfig.setTransactional(true);
133         dbConfig.setAllowCreate(true);
134         dbConfig.setSortedDuplicates(true);
135         Database exampleDb = exampleEnv.openDatabase(txn,
136                                                      "simpleDb",
137                                                      dbConfig);
138         txn.commit();
139 
140         /*
141          * Insert or retrieve data. In our example, database records are
142          * integer pairs.
143          */
144 
145         /* DatabaseEntry represents the key and data of each record */
146         DatabaseEntry keyEntry = new DatabaseEntry();
147         DatabaseEntry dataEntry = new DatabaseEntry();
148 
149         if (doInsert) {
150 
151             /* put some data in */
152             for (int i = offset; i < numRecords + offset; i++) {
153                 /*
154                  * Note that autocommit mode, described in the Getting
155                  * Started Guide, is an alternative to explicitly
156                  * creating the transaction object.
157                  */
158                 txn = exampleEnv.beginTransaction(null, null);
159 
160                 /* Use a binding to convert the int into a DatabaseEntry. */
161 
162                 IntegerBinding.intToEntry(i, keyEntry);
163                 IntegerBinding.intToEntry(i+1, dataEntry);
164                 OperationStatus status =
165                     exampleDb.put(txn, keyEntry, dataEntry);
166 
167                 /*
168                  * Note that put will throw a DatabaseException when
169                  * error conditions are found such as deadlock.
170                  * However, the status return conveys a variety of
171                  * information. For example, the put might succeed,
172                  * or it might not succeed if the record alread exists
173                  * and the database was not configured for duplicate
174                  * records.
175                  */
176                 if (status != OperationStatus.SUCCESS) {
177                     throw new RuntimeException("Data insertion got status " +
178                                                status);
179                 }
180                 txn.commit();
181             }
182         } else {
183             /* retrieve the data */
184             Cursor cursor = exampleDb.openCursor(null, null);
185 
186             while (cursor.getNext(keyEntry, dataEntry, LockMode.DEFAULT) ==
187                    OperationStatus.SUCCESS) {
188                 System.out.println("key=" +
189                                    IntegerBinding.entryToInt(keyEntry) +
190                                    " data=" +
191                                    IntegerBinding.entryToInt(dataEntry));
192 
193             }
194             cursor.close();
195         }
196 
197         exampleDb.close();
198         exampleEnv.close();
199 
200     }
201 }
202