Fixing Bugs
[iotcloud.git] / version2 / src / 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     public long getArbitrator() {
61         return arbitrator;
62     }
63
64     /**
65      * Get the key value update set
66      *
67      */
68     public Set<KeyValue> getKVUpdates() {
69         return keyValueUpdateSet;
70     }
71
72     /**
73     * Get the guard
74     *
75     */
76     public Guard getGuard() {
77         return guard;
78     }
79
80     /**
81      * Add a guard to this transaction
82      *
83      */
84     public void addGuard(Guard _guard) {
85         guard = _guard;
86     }
87
88     /**
89      * Evaluate the guard expression for a given transaction using a set of key value pairs.
90      *
91      */
92     public boolean evaluate(Set<KeyValue> kvSet) throws ScriptException, NullPointerException {
93
94         // Evaluate the guard using the current KV Set
95         return guard.evaluate(kvSet);
96     }
97
98     /**
99      * Add a boolean expression to the guard.
100      *
101      */
102     public void setGuardExpression(String expr) {
103         guard.setGuardExpression(expr);
104     }
105
106     /**
107      * Trampoline static method.
108      *
109      */
110     public static String createExpression(IoTString keyName, IoTString keyValue, byte op) {
111         return Guard.createExpression(keyName, keyValue, op);
112     }
113 }