Squashed Last bugs
[iotcloud.git] / version2 / src / 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 = null;
12     private Guard guard;
13     private Long arbitrator;
14
15     public Transaction(Slot slot, long _seqnum, long _machineid, Long _arbitrator, Set<KeyValue> _keyValueUpdateSet, Guard _guard) {
16         super(slot);
17         seqnum = _seqnum;
18         machineid = _machineid;
19         arbitrator = _arbitrator;
20         keyValueUpdateSet = new HashSet<KeyValue>();
21
22         for (KeyValue kv : _keyValueUpdateSet) {
23             KeyValue kvCopy = kv.getCopy();
24             keyValueUpdateSet.add(kvCopy);
25         }
26
27         guard = _guard.getCopy();
28     }
29
30     public long getMachineID() {
31         return machineid;
32     }
33
34     public long getArbitrator() {
35         return arbitrator;
36     }
37
38     public long getSequenceNumber() {
39         return seqnum;
40     }
41
42     public Set<KeyValue> getkeyValueUpdateSet() {
43         return keyValueUpdateSet;
44     }
45
46     public Guard getGuard() {
47         return guard;
48     }
49
50     public byte getType() {
51         return Entry.TypeTransaction;
52     }
53
54     public int getSize() {
55         int size = 3 * Long.BYTES + Byte.BYTES; // seq, machine id, entry type
56         size += Integer.BYTES; // number of KV's
57
58         // Size of each KV
59         for (KeyValue kv : keyValueUpdateSet) {
60             size += kv.getSize();
61         }
62
63         // Size of the guard
64         size += guard.getSize();
65
66         return size;
67     }
68
69
70     public void encode(ByteBuffer bb) {
71         bb.put(Entry.TypeTransaction);
72         bb.putLong(seqnum);
73         bb.putLong(machineid);
74         bb.putLong(arbitrator);
75
76         bb.putInt(keyValueUpdateSet.size());
77         for (KeyValue kv : keyValueUpdateSet) {
78             kv.encode(bb);
79         }
80
81         guard.encode(bb);
82     }
83
84     static Entry decode(Slot slot, ByteBuffer bb) {
85         long seqnum = bb.getLong();
86         long machineid = bb.getLong();
87         long arbitrator = bb.getLong();
88         int numberOfKeys = bb.getInt();
89
90         Set<KeyValue> kvSet = new HashSet<KeyValue>();
91         for (int i = 0; i < numberOfKeys; i++) {
92             KeyValue kv = KeyValue.decode(bb);
93             kvSet.add(kv);
94         }
95
96         Guard guard = Guard.decode(bb);
97
98         return new Transaction(slot, seqnum, machineid, arbitrator, kvSet, guard);
99     }
100
101     public Entry getCopy(Slot s) {
102         return new Transaction(s, seqnum, machineid, arbitrator, keyValueUpdateSet, guard);
103     }
104 }