Initial commit of code for new version of block chain, does not compile (had to go...
[iotcloud.git] / src2 / java / iotcloud / Transaction.java
1 package iotcloud;
2
3 import java.nio.ByteBuffer;
4 import java.util.Set;
5 import java.util.HashSet;
6
7 class Transaction extends Entry {
8
9     private long seqnum;
10     private long machineid;
11     private Set<KeyValue> keyValueUpdateSet;
12     private Guard guard;
13
14     public Transaction(Slot slot, long _seqnum, long _machineid, Set<KeyValue> _keyValueUpdateSet, Guard _guard) {
15         super(slot);
16         seqnum = _seqnum;
17         machineid = _machineid;
18         keyValueUpdateSet = _keyValueUpdateSet;
19         guard = _guard;
20     }
21
22     public long getMachineID() {
23         return machineid;
24     }
25
26     public long getSequenceNumber() {
27         return seqnum;
28     }
29
30     public byte getType() {
31         return Entry.TypeLastMessage;
32     }
33
34     public int getSize() {
35         int size = 2 * Long.BYTES + Byte.BYTES; // seq, machine id, entry type
36         size += Integer.BYTES; // number of KV's
37
38         // Size of each KV
39         for (KeyValue kv : keyValueUpdateSet) {
40             size += kv.getSize();
41         }
42
43         // Size of the guard
44         size += guard.getSize();
45
46         return size;
47     }
48
49
50     public void encode(ByteBuffer bb) {
51         bb.put(Entry.TypeTransaction);
52         bb.putLong(seqnum);
53         bb.putLong(machineid);
54
55         for (KeyValue kv : keyValueUpdateSet) {
56             kv.encode(bb);
57         }
58
59         guard.encode(bb);
60     }
61
62     static Entry decode(Slot slot, ByteBuffer bb) {
63         long seqnum = bb.getLong();
64         long machineid = bb.getLong();
65         int numberOfKeys = bb.getInt();
66
67         Set<KeyValue> kvSet = new HashSet<KeyValue>();
68
69         for (int i = 0; i < numberOfKeys; i++) {
70             KeyValue kv = KeyValue.decode(bb);
71             kvSet.add(kv);
72         }
73
74         Guard guard = Guard.decode(bb);
75
76         return new Transaction(slot, seqnum, machineid, kvSet, guard);
77     }
78
79
80
81     public Entry getCopy(Slot s) {
82         return new Transaction(s, seqnum, machineid, keyValueUpdateSet, guard);
83     }
84 }