3d39e12559ac3270d1e9c35cb05187215ae904d8
[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         // Make sure there are no duplicates
31         for (KeyValue kv : keyValueUpdateSet) {
32             if (kv.getKey().equals(newKV.getKey())) {
33
34                 // Remove key if we are adding a newer version of the same key
35                 keyValueUpdateSet.remove(kv);
36                 break;
37             }
38         }
39
40         // Add the key to the hash set
41         keyValueUpdateSet.add(newKV);
42     }
43
44     public boolean checkArbitrator(long arb) {
45         if (arbitrator == -1) {
46             arbitrator = arb;
47             return true;
48         }
49
50         return arb == arbitrator;
51     }
52
53
54
55     /**
56      * Get the key value update set
57      *
58      */
59     public Set<KeyValue> getKVUpdates() {
60         return keyValueUpdateSet;
61     }
62
63     /**
64     * Get the guard
65     *
66     */
67     public Guard getGuard() {
68         return guard;
69     }
70
71     /**
72      * Add a guard to this transaction
73      *
74      */
75     public void addGuard(Guard _guard) {
76         guard = _guard;
77     }
78
79     /**
80      * Evaluate the guard expression for a given transaction using a set of key value pairs.
81      *
82      */
83     public boolean evaluate(Set<KeyValue> kvSet) throws ScriptException, NullPointerException {
84
85         // Evaluate the guard using the current KV Set
86         return guard.evaluate(kvSet);
87     }
88
89     /**
90      * Add a boolean expression to the guard.
91      *
92      */
93     public void setGuardExpression(String expr) {
94         guard.setGuardExpression(expr);
95     }
96
97     /**
98      * Trampoline static method.
99      *
100      */
101     public static String createExpression(IoTString keyName, IoTString keyValue, byte op) {
102         return Guard.createExpression(keyName, keyValue, op);
103     }
104 }