// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import com.sleepycat.je.Cursor;
import com.sleepycat.je.CursorConfig;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.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 b) throws IOException, ClassNotFoundException {
        ByteBuffer bb = ByteBuffer.wrap(b.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 {
        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 int NREC = 1000;
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // open database
        EnvironmentConfig envcfg = new EnvironmentConfig();
        envcfg.setAllowCreateVoid(true);
        Environment env = new Environment(new File("data/"), envcfg);
        DatabaseConfig dbcfg = new DatabaseConfig();
        dbcfg.setAllowCreate(true);
        Database db = env.openDatabase(null, "testdb", dbcfg);
        // put data
        for(int i = 0; i < NREC; i++) {
            String key = "Key#" + (1000 + 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#" + 1077;
        // get
        dump(db, key);
        // delete
        db.delete(null, prep(key));
        // get non existing
        dump(db, key);
        //
        key = "Key#" + 1088;
        // 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, new CursorConfig());
        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, new CursorConfig());
        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);
        // close database
        db.close();
        env.close();
    }
}
