5253a94f841cc7c36c5e70c88e78ee67a9a9400e
[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
18     public PendingTransaction() {
19         keyValueUpdateSet = new HashSet<KeyValue>();
20         guard = new Guard();
21     }
22
23     /**
24      * Add a new key value to the updates
25      *
26      */
27     public void addKV(KeyValue newKV) {
28
29         // Make sure there are no duplicates
30         for (KeyValue kv : keyValueUpdateSet) {
31             if (kv.getKey().equals(newKV.getKey())) {
32
33                 // Remove key if we are adding a newer version of the same key
34                 keyValueUpdateSet.remove(kv);
35                 break;
36             }
37         }
38
39         // Add the key to the hash set
40         keyValueUpdateSet.add(newKV);
41     }
42
43     /**
44      * Get the key value update set
45      *
46      */
47     public Set<KeyValue> getKVUpdates() {
48         return keyValueUpdateSet;
49     }
50
51     /**
52     * Get the guard
53     *
54     */
55     public Guard getGuard() {
56         return guard;
57     }
58
59     /**
60      * Add a guard to this transaction
61      *
62      */
63     public void addGuard(Guard _guard) {
64         guard = _guard;
65     }
66
67     /**
68      * Evaluate the guard expression for a given transaction using a set of key value pairs.
69      *
70      */
71     public boolean evaluate(Set<KeyValue> kvSet) throws ScriptException, NullPointerException {
72
73         // Evaluate the guard using the current KV Set
74         return guard.evaluate(kvSet);
75     }
76
77     /**
78      * Add a boolean expression to the guard.
79      *
80      */
81     public void setGuardExpression(String expr) {
82         guard.setGuardExpression(expr);
83     }
84
85     /**
86      * Trampoline static method.
87      *
88      */
89     public static String createExpression(IoTString keyName, IoTString keyValue, byte op) {
90         return Guard.createExpression(keyName, keyValue, op);
91     }
92 }