// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
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 BigDecimal readBCD(byte[] b, int scale) {
        long res = 0;
        for(int i = 0; i < b.length; i++) {
            int upp = (b[i] & 0xF0) >> 4;
            int low = b[i] & 0x0F;
            res = res * 10 + upp;
            if(low <= 10) {
                res = res * 10 + low;
            } else {
                if(low == 11 | low == 13) res = -res;
            }
        }
        return new BigDecimal(res).divide(new BigDecimal(10).pow(scale)).setScale(scale);
    }
    private static byte[] writeBCD(BigDecimal v, int scale, int n) {
        byte[] res = new byte[n];
        long tmp = v.multiply(new BigDecimal(10).pow(scale)).longValue();
        for(int i = n - 1; i >= 0; i--) {
            long low;
            if(i == n - 1) {
                low = 0x0F; /* assume unsigned */
            } else {
                low = tmp % 10;
                tmp = tmp / 10;
            }
            long upp = tmp % 10;
            tmp = tmp / 10;
            res[i] = (byte)((upp << 4) | low);
        }
        return res;
    }
    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.BIG_ENDIAN);
        bb.put(o.getId().getBytes("UTF-8"));
        bb.putInt(o.getIv());
        bb.put(writeBCD(o.getZv(), 2, 4));
        bb.order(ByteOrder.LITTLE_ENDIAN); // double is not in big endian
        bb.putDouble(o.getXv());
        bb.order(ByteOrder.BIG_ENDIAN);
        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.BIG_ENDIAN);
        byte[] temp = new byte[8];
        bb.get(temp);
        String id = new String(temp, "UTF-8");
        int iv = bb.getInt();
        temp = new byte[4];
        bb.get(temp);
        BigDecimal zv = readBCD(temp, 2);
        bb.order(ByteOrder.LITTLE_ENDIAN); // double is not in big endian
        double xv = bb.getDouble();
        bb.order(ByteOrder.BIG_ENDIAN);
        int len = bb.getShort();
        temp = new byte[len];
        bb.get(temp);
        String sv = new String(temp, "UTF-8");
        Data res = new Data(id, iv, zv, 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 = "testdb.isq";
    private static final int NREC = 1000;
    private static final int JAVA_OFFSET = 4 * 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.setId(key);
             value.setIv(i + 1);
             value.setZv(new BigDecimal(i + 1).setScale(2));
             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.setZv(value.getZv().add(new BigDecimal("0.10")));
         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() ||
                itvalue.getZv().compareTo(BigDecimal.ONE) < 0 || new BigDecimal(NREC).compareTo(itvalue.getZv()) < 0 ||
                itvalue.getXv() < 1 || NREC < itvalue.getXv()) {
                 System.out.println("Unexpected value: " + itvalue);
             }
             n++;
             itstat = it.getNext(itrawkey, itrawvalue, null);
         }
         it.close();
         System.out.println(n);
         // list keys where "Key#n075" <= key < "Key#n085"
         Cursor it2 = db.openCursor(null, null);
         DatabaseEntry it2rawkey = prep("Key#" + (JAVA_OFFSET + 75));
         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#" + (JAVA_OFFSET + 85)) >= 0) break;
             n2++;
             it2stat = it2.getNext(it2rawkey, it2rawvalue, null);
         }
         it2.close();
         System.out.println(n2);
         //
         db.close();
    }
}
