HelloDatabaseWorld.java [plain text]
package collections.hello;
import java.io.File;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import com.sleepycat.bind.serial.ClassCatalog;
import com.sleepycat.bind.serial.SerialBinding;
import com.sleepycat.bind.serial.StoredClassCatalog;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.collections.StoredSortedMap;
import com.sleepycat.collections.TransactionRunner;
import com.sleepycat.collections.TransactionWorker;
import com.sleepycat.db.Database;
import com.sleepycat.db.DatabaseConfig;
import com.sleepycat.db.DatabaseType;
import com.sleepycat.db.Environment;
import com.sleepycat.db.EnvironmentConfig;
public class HelloDatabaseWorld implements TransactionWorker {
private static final String[] INT_NAMES = {
"Hello", "Database", "World",
};
private static boolean create = true;
private Environment env;
private ClassCatalog catalog;
private Database db;
private SortedMap map;
public static void main(String[] argv)
throws Exception {
String dir = "./tmp";
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setTransactional(true);
envConfig.setInitializeCache(true);
envConfig.setInitializeLocking(true);
if (create) {
envConfig.setAllowCreate(true);
}
Environment env = new Environment(new File(dir), envConfig);
HelloDatabaseWorld worker = new HelloDatabaseWorld(env);
TransactionRunner runner = new TransactionRunner(env);
try {
runner.run(worker);
} finally {
worker.close();
}
}
private HelloDatabaseWorld(Environment env)
throws Exception {
this.env = env;
open();
}
public void doWork()
throws Exception {
writeAndRead();
}
private void open()
throws Exception {
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setTransactional(true);
if (create) {
dbConfig.setAllowCreate(true);
dbConfig.setType(DatabaseType.BTREE);
}
Database catalogDb = env.openDatabase(null, "catalog", null, dbConfig);
catalog = new StoredClassCatalog(catalogDb);
TupleBinding keyBinding =
TupleBinding.getPrimitiveBinding(Integer.class);
SerialBinding dataBinding = new SerialBinding(catalog, String.class);
this.db = env.openDatabase(null, "helloworld", null, dbConfig);
this.map = new StoredSortedMap(db, keyBinding, dataBinding, true);
}
private void close()
throws Exception {
if (catalog != null) {
catalog.close();
catalog = null;
}
if (db != null) {
db.close();
db = null;
}
if (env != null) {
env.close();
env = null;
}
}
private void writeAndRead() {
Integer key = new Integer(0);
String val = (String) map.get(key);
if (val == null) {
System.out.println("Writing data");
for (int i = INT_NAMES.length - 1; i >= 0; i -= 1) {
map.put(new Integer(i), INT_NAMES[i]);
}
}
Iterator iter = map.entrySet().iterator();
System.out.println("Reading data");
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
System.out.println(entry.getKey().toString() + ' ' +
entry.getValue());
}
}
}