// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package nosql.bdb;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import com.sleepycat.db.Cursor;
import com.sleepycat.db.Database;
import com.sleepycat.db.DatabaseConfig;
import com.sleepycat.db.DatabaseEntry;
import com.sleepycat.db.DatabaseException;
import com.sleepycat.db.OperationStatus;

public class Test {
    private static DatabaseEntry prep(String key) throws UnsupportedEncodingException {
        return new DatabaseEntry(key.getBytes("UTF-8"));
    }
    private static DatabaseEntry serialize(Data o) throws IOException {
        ByteBuffer bb = ByteBuffer.allocate(1000);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.putInt(o.getIv());
        bb.putDouble(o.getXv());
        byte[] b = o.getSv().getBytes("UTF-8");
        bb.putShort((short)b.length);
        bb.put(b);
        int n = bb.position();
        byte[] res = new byte[n];
        bb.rewind();
        bb.get(res);
        return new DatabaseEntry(res);
    }
    private static Data deserialize(DatabaseEntry de) throws IOException, ClassNotFoundException {
        ByteBuffer bb = ByteBuffer.wrap(de.getData());
        bb.order(ByteOrder.LITTLE_ENDIAN);
        int iv = bb.getInt();
        double xv = bb.getDouble();
        int len = bb.getShort();
        byte[] temp = new byte[len];
        bb.get(temp);
        String sv = new String(temp, "UTF-8");
        Data res = new Data(iv, xv, sv);
        return res;
    }
    private static void dump(Database db, String key) throws ClassNotFoundException, IOException, DatabaseException {
        System.out.printf("Key=%s\n", key);
        DatabaseEntry rawvalue = new DatabaseEntry();
        if(db.get(null, prep(key), rawvalue, null) == OperationStatus.SUCCESS) {
            Data value = deserialize(rawvalue);
            System.out.println(value);
        } else {
            System.out.println("Not found");
        }
    }
    private static final String DBNAME = "/work/bdb/test.db";
    private static final int NREC = 1000;
    private static final int JAVA_OFFSET = 2 * NREC;
    public static void main(String[] args) throws DatabaseException, UnsupportedEncodingException, IOException, ClassNotFoundException {
         Database db = new Database(DBNAME, null, new DatabaseConfig());
         // put data
         for(int i = 0; i < NREC; i++) {
             String key = "Key#" + (JAVA_OFFSET + i + 1);
             Data value = new Data();
             value.setIv(i + 1);
             value.setXv(i + 1.0);
             value.setSv(String.format("This is value %d", i + 1));
             db.put(null, prep(key), serialize(value));
         }
         //
         String key;
         key = "Key#" + (JAVA_OFFSET + 77);
         // get
         dump(db, key);
         // delete
         db.delete(null, prep(key));
         // get non existing
         dump(db, key);
         //
         key = "Key#" + (JAVA_OFFSET + 88);
         // update and get
         dump(db, key);
         DatabaseEntry rawvalue = new DatabaseEntry();
         db.get(null, prep(key), rawvalue, null);
         Data value = (Data)deserialize(rawvalue);
         value.setIv(value.getIv() + 1);
         value.setXv(value.getXv() + 0.1);
         value.setSv(value.getSv() + " updated");
         db.put(null, prep(key), serialize(value));
         dump(db, key);
         // list all
         Cursor it = db.openCursor(null, null);
         DatabaseEntry itrawkey = new DatabaseEntry();
         DatabaseEntry itrawvalue = new DatabaseEntry();
         OperationStatus itstat = it.getFirst(itrawkey, itrawvalue, null);
         int n = 0;
         while(itstat == OperationStatus.SUCCESS) {
             String itkey = new String(itrawkey.getData(), "UTF-8");
             if(!itkey.startsWith("Key#")) {
                 System.out.println("Unexpected key: " + itkey);
             }
             Data itvalue = (Data)deserialize(itrawvalue);
             if(itvalue.getIv() < 1 || NREC < itvalue.getIv()) {
                 System.out.println("Unexpected value :" + itvalue);
             }
             n++;
             itstat = it.getNext(itrawkey, itrawvalue, null);
         }
         it.close();
         System.out.println(n);
         // list keys where "Key#1075" <= key < "Key#1085"
         Cursor it2 = db.openCursor(null, null);
         DatabaseEntry it2rawkey = prep("Key#" + 1075);
         DatabaseEntry it2rawvalue = new DatabaseEntry();
         OperationStatus it2stat = it2.getSearchKey(it2rawkey, it2rawvalue, null);
         int n2 = 0;
         while(it2stat == OperationStatus.SUCCESS) {
             String it2key = new String(it2rawkey.getData(), "UTF-8");
             if(it2key.compareTo("Key#" + 1085) >= 0) break;
             n2++;
             it2stat = it2.getNext(it2rawkey, it2rawvalue, null);
         }
         it2.close();
         System.out.println(n2);
         //
         db.close();
    }
}
