In my last post, I have mentioned about what a key-value store database and little about Sleepycat. While Sleepycat is great, it needs some configuration before actually using it. For this reason, I have written an wrapper which stores only unicode-based strings as key and value. The code is given in the following Gist. The usage example has been given in the comment.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package models; | |
import java.io.File; | |
import java.io.UnsupportedEncodingException; | |
import com.sleepycat.je.Database; | |
import com.sleepycat.je.DatabaseConfig; | |
import com.sleepycat.je.DatabaseEntry; | |
import com.sleepycat.je.DatabaseException; | |
import com.sleepycat.je.Environment; | |
import com.sleepycat.je.EnvironmentConfig; | |
import com.sleepycat.je.LockMode; | |
import com.sleepycat.je.Transaction; | |
import com.sleepycat.je.txn.Txn; | |
/* | |
* KeyStore config = new KeyStore(); | |
* config.put("name", "Dagvadorj"); | |
* config.commit(); | |
* String name = config.get("name"); | |
* config.close(); | |
*/ | |
public class KeyStore { | |
private static EnvironmentConfig environmentConfig; | |
private static Environment environ; | |
private static DatabaseConfig databaseConfig; | |
private static Database db; | |
private static Transaction txn; | |
public KeyStore() { | |
environmentConfig = new EnvironmentConfig(); | |
environmentConfig.setAllowCreate(true); | |
environmentConfig.setTransactional(true); | |
environ = new Environment(new File("configdb"), environmentConfig); | |
databaseConfig = new DatabaseConfig(); | |
databaseConfig.setAllowCreate(true); | |
databaseConfig.setTransactional(true); | |
txn = environ.beginTransaction(null, null); | |
db = environ.openDatabase(null, "Navigator", | |
databaseConfig); | |
} | |
public static String get(String key) { | |
DatabaseEntry keyEntry = new DatabaseEntry(); | |
DatabaseEntry dataEntry = new DatabaseEntry(); | |
try { | |
keyEntry.setData(key.getBytes("utf-8")); | |
} catch (UnsupportedEncodingException e) { | |
return null; | |
} | |
db.get(null, keyEntry, dataEntry, LockMode.DEFAULT); | |
try { | |
byte [] data = dataEntry.getData(); | |
if (data == null) return null; | |
return new String(dataEntry.getData(), "utf-8"); | |
} catch (UnsupportedEncodingException e) { | |
return null; | |
} | |
} | |
public static boolean put(String key, String value) { | |
try { | |
db.put(null, new DatabaseEntry(key.getBytes("utf-8")), | |
new DatabaseEntry(value.getBytes("utf-8"))); | |
} catch (DatabaseException e) { | |
return false; | |
} catch (UnsupportedEncodingException e){ | |
return false; | |
} | |
return true; | |
} | |
public static void commit() { | |
txn.commit(); | |
} | |
public static void close() { | |
db.close(); | |
environ.close(); | |
} | |
} |