4 import java.util.HashSet;
5 import java.util.Collection;
6 import java.nio.ByteBuffer;
8 import javax.script.ScriptEngine;
9 import javax.script.ScriptEngineManager;
10 import javax.script.ScriptException;
11 import java.lang.NullPointerException;
16 static final byte Equal = 1;
17 static final byte NotEqual = 2;
19 private IoTString booleanExpression;
22 booleanExpression = null;
25 public Guard(IoTString _booleanExpression) {
26 booleanExpression = _booleanExpression;
30 * Create an equality expression for a key value.
33 public static String createExpression(IoTString keyName, IoTString keyValue, byte op) {
35 return keyName.toString() + "=='" + keyValue.toString() + "'";
36 } else if (op == NotEqual) {
37 return keyName.toString() + "!='" + keyValue.toString() + "'";
45 * Add a boolean expression to the guard.
48 public void setGuardExpression(String expr) {
49 booleanExpression = new IoTString(expr);
53 * Evaluate the guard expression for a given set of key value pairs.
56 public boolean evaluate(Collection<KeyValue> kvSet) throws ScriptException, NullPointerException {
58 // There are no conditions to evaluate
59 if (booleanExpression == null) {
63 // All the current key value pairs that we need to evaluate the condition
64 String[] variables = new String[kvSet.size()];
66 // Fill the variables array
68 for (KeyValue kv : kvSet) {
69 variables[i] = kv.getKey() + " ='" + kv.getValue() + "'";
73 // Prep the evaluation engine (script engine)
74 ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
75 for (String s : variables) {
79 // Evaluate the guard condition
80 return 1 == (Integer)engine.eval(booleanExpression.toString());
84 * Get the size of the guard condition
87 public int getSize() {
89 if (booleanExpression == null) {
93 return Integer.BYTES + booleanExpression.length();
96 public void encode(ByteBuffer bb) {
97 if (booleanExpression == null) {
100 bb.putInt(booleanExpression.length());
101 bb.put(booleanExpression.internalBytes());
105 static Guard decode(ByteBuffer bb) {
106 int exprLength = bb.getInt();
108 if (exprLength != 0) {
109 byte[] expr = new byte[exprLength];
111 return new Guard(IoTString.shallow(expr));
113 return new Guard(null);
116 public Guard getCopy() {
118 if (booleanExpression == null) {
119 return new Guard(null);
122 return new Guard(IoTString.shallow(booleanExpression.internalBytes()));