Initial Working version of IoTCloudv2, needs more testing
[iotcloud.git] / src2 / java / iotcloud / PendingTransaction.java
1 package iotcloud;
2
3 import java.util.Set;
4 import java.util.HashSet;
5
6 import javax.script.ScriptException;
7 import java.lang.NullPointerException;
8
9
10 class PendingTransaction {
11
12     static final byte Equal = Guard.Equal;
13     static final byte NotEqual = Guard.NotEqual;
14
15     private Set<KeyValue> keyValueUpdateSet;
16     private Guard guard;
17     private long arbitrator = -1;
18
19     public PendingTransaction() {
20         keyValueUpdateSet = new HashSet<KeyValue>();
21         guard = new Guard();
22     }
23
24     /**
25      * Add a new key value to the updates
26      *
27      */
28     public void addKV(KeyValue newKV) {
29
30         KeyValue rmKV = null;
31
32         // Make sure there are no duplicates
33         for (KeyValue kv : keyValueUpdateSet) {
34             if (kv.getKey().equals(newKV.getKey())) {
35
36                 // Remove key if we are adding a newer version of the same key
37                 rmKV = kv;
38                 break;
39             }
40         }
41
42         // Remove key if we are adding a newer version of the same key
43         if (rmKV != null) {
44             keyValueUpdateSet.remove(rmKV);
45         }
46
47         // Add the key to the hash set
48         keyValueUpdateSet.add(newKV);
49     }
50
51     public boolean checkArbitrator(long arb) {
52         if (arbitrator == -1) {
53             arbitrator = arb;
54             return true;
55         }
56
57         return arb == arbitrator;
58     }
59
60
61
62     /**
63      * Get the key value update set
64      *
65      */
66     public Set<KeyValue> getKVUpdates() {
67         return keyValueUpdateSet;
68     }
69
70     /**
71     * Get the guard
72     *
73     */
74     public Guard getGuard() {
75         return guard;
76     }
77
78     /**
79      * Add a guard to this transaction
80      *
81      */
82     public void addGuard(Guard _guard) {
83         guard = _guard;
84     }
85
86     /**
87      * Evaluate the guard expression for a given transaction using a set of key value pairs.
88      *
89      */
90     public boolean evaluate(Set<KeyValue> kvSet) throws ScriptException, NullPointerException {
91
92         // Evaluate the guard using the current KV Set
93         return guard.evaluate(kvSet);
94     }
95
96     /**
97      * Add a boolean expression to the guard.
98      *
99      */
100     public void setGuardExpression(String expr) {
101         guard.setGuardExpression(expr);
102     }
103
104     /**
105      * Trampoline static method.
106      *
107      */
108     public static String createExpression(IoTString keyName, IoTString keyValue, byte op) {
109         return Guard.createExpression(keyName, keyValue, op);
110     }
111 }