4 import java.util.HashSet;
5 import java.nio.ByteBuffer;
7 import javax.script.ScriptEngine;
8 import javax.script.ScriptEngineManager;
9 import javax.script.ScriptException;
10 import java.lang.NullPointerException;
15 static final byte Equal = 1;
16 static final byte NotEqual = 2;
18 private IoTString booleanExpression;
21 booleanExpression = null;
24 public Guard(IoTString _booleanExpression) {
25 booleanExpression = _booleanExpression;
29 * Create an equality expression for a key value.
32 public static String createExpression(IoTString keyName, IoTString keyValue, byte op) {
34 return keyName.toString() + "=='" + keyValue.toString() + "'";
35 } else if (op == NotEqual) {
36 return keyName.toString() + "!='" + keyValue.toString() + "'";
44 * Add a boolean expression to the guard.
47 public void setGuardExpression(String expr) {
48 booleanExpression = new IoTString(expr);
52 * Evaluate the guard expression for a given set of key value pairs.
55 public boolean evaluate(Set<KeyValue> kvSet) throws ScriptException, NullPointerException {
57 // There are no conditions to evaluate
58 if (booleanExpression == null) {
62 // All the current key value pairs that we need to evaluate the condition
63 String[] variables = new String[kvSet.size()];
65 // Fill the variables array
67 for (KeyValue kv : kvSet) {
68 variables[i] = kv.getKey() + " ='" + kv.getValue() + "'";
72 // Prep the evaluation engine (script engine)
73 ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
74 for (String s : variables) {
78 // Evaluate the guard condition
79 return 1 == (Integer)engine.eval(booleanExpression.toString());
83 * Get the size of the guard condition
86 public int getSize() {
87 return Integer.BYTES + booleanExpression.length();
90 public void encode(ByteBuffer bb) {
91 bb.putInt(booleanExpression.length());
92 bb.put(booleanExpression.internalBytes());
95 static Guard decode(ByteBuffer bb) {
96 int exprLength = bb.getInt();
97 byte[] expr = new byte[exprLength];
99 return new Guard(IoTString.shallow(expr));
102 public Guard getCopy() {
103 return new Guard(IoTString.shallow(booleanExpression.internalBytes()));