forked from IBM/JSONata4Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpression.java
More file actions
582 lines (551 loc) · 23.4 KB
/
Copy pathExpression.java
File metadata and controls
582 lines (551 loc) · 23.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
/**
*
*/
package com.api.jsonata4java;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.api.jsonata4java.expressions.EvaluateException;
import com.api.jsonata4java.expressions.EvaluateRuntimeException;
import com.api.jsonata4java.expressions.Expressions;
import com.api.jsonata4java.expressions.ExpressionsVisitor;
import com.api.jsonata4java.expressions.FrameEnvironment;
import com.api.jsonata4java.expressions.ParseException;
import com.api.jsonata4java.expressions.functions.DeclaredFunction;
import com.api.jsonata4java.expressions.generated.MappingExpressionParser.ExprContext;
import com.api.jsonata4java.expressions.regex.RegexEngine;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
/**
* Class to provide embedding and extending JSONata features
*/
public class Expression implements Serializable {
private static final long serialVersionUID = -292660522621832862L;
/**
* Establish a list of bindings for the given json object
*
* @param bindingObj
* the json to calculate the bindings for
* @return the list of bindings for the provided json
* @throws ParseException
*/
public static List<Binding> createBindings(JsonNode bindingObj) throws ParseException {
ObjectMapper objectMapper = new ObjectMapper();
List<Binding> bindings = new ArrayList<Binding>();
for (Iterator<String> it = bindingObj.fieldNames(); it.hasNext();) {
String key = it.next();
JsonNode testObj = bindingObj.get(key);
String expression = "";
try {
if (testObj.isTextual() == false) {
expression = testObj.toString();
Binding binding = new Binding(key, expression);
bindings.add(binding);
} else {
// if the string starts with function treat as an expression
expression = objectMapper.writeValueAsString(testObj).trim();
while (expression.startsWith("\"") && expression.length() > 1) {
expression = expression.substring(1);
}
while (expression.endsWith("\"") && expression.length() > 1) {
expression = expression.substring(0, expression.length() - 1);
}
Binding binding = null;
if (expression.startsWith("function")) {
binding = new Binding(key, expression);
} else {
binding = new Binding(key, testObj);
}
bindings.add(binding);
}
} catch (Exception e) {
Binding binding = new Binding(key, testObj);
bindings.add(binding);
}
}
return bindings;
}
/**
* Generate a new Expression based on evaluating the supplied expression
*
* @param expression
* the logic to be parsed for later execution via the evaluate
* methods
* @return new Expression object
* @throws ParseException
* @throws IOException
*/
public static Expression jsonata(String expression) throws ParseException, IOException {
return new Expression(expression);
}
/**
* Generate a new Expression based on evaluating the supplied expression,
* using a custom regex engine to compile any regex literals or dynamic
* string patterns encountered (e.g. for $match/$replace/$split) instead of
* the default {@link java.util.regex.Pattern}-backed one.
*
* @param expression
* the logic to be parsed for later execution via the evaluate
* methods
* @param regexEngine
* the regex engine to use
* @return new Expression object
* @throws ParseException
* @throws IOException
*/
public static Expression jsonata(String expression, RegexEngine regexEngine) throws ParseException, IOException {
return new Expression(expression, regexEngine);
}
/**
* Testing the various methods based on
* https://docs.jsonata.org/embedding-extending#expressionregisterfunctionname-implementation-signature
*
* @param args
* not used
*/
public static void main(String[] args) {
try {
String exprString = "$sum(example.value)";
String inputString = "{\"example\": [{\"value\": 4}, {\"value\": 7}, {\"value\": 13}]}";
System.out.println("Expression is " + exprString);
System.out.println("Input is " + inputString);
Expression expression = Expression.jsonata(exprString);
JsonNode obj = new ObjectMapper().readTree(inputString);
JsonNode result = expression.evaluate(obj);
System.out.println("Result is " + result);
expression = Expression.jsonata("$a +$b()");
expression.assign("a", "4");
expression.assign("$b", "function(){1}");
result = expression.evaluate(obj);
System.out.println("Input is \"$a + $b()\" with assignments \"a\":4, \"$b\":\"function(){1}\"");
System.out.println("Result is " + result);
JsonNode bindingObj = new ObjectMapper().readTree("{\"a\":4, \"b\":\"function(){78}\"}");
System.out.println("Input is \"$a + $b()\" with binding object: " + bindingObj.toString());
System.out.println("Result is " + Expression.jsonata("$a + $b()").evaluate(obj, bindingObj));
bindingObj = new ObjectMapper().readTree("{\"a\":4, \"b\":\"function($c){$c+78}\",\"c\":7}");
System.out.println("Input is \"$a + $b($c)\" with binding object: " + bindingObj.toString());
System.out.println("Result is " + Expression.jsonata("$a + $b($c)").evaluate(obj, bindingObj));
try {
expression = Expression.jsonata("$notafunction()");
result = expression.evaluate(JsonNodeFactory.instance.objectNode());
throw new Exception("Expression " + expression + " should have generated an exception");
} catch (EvaluateRuntimeException ere) {
System.out
.println("Result is we got the expected EvaluateRuntimeException for " + ere.getLocalizedMessage());
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Map<String, DeclaredFunction> _declaredFunctionMap = new HashMap<String, DeclaredFunction>();
ExpressionsVisitor _eval = null;
Expressions _expr = null;
Map<String, ExprContext> _variableMap = new HashMap<String, ExprContext>();
RegexEngine _regexEngine = RegexEngine.defaultEngine();
/**
* Constructor for Expression
*
* @param expression
* the logic to be parsed for later execution via evaluate
* methods
* @throws ParseException
* @throws IOException
*/
public Expression(String expression) throws ParseException, IOException {
_expr = Expressions.parse(expression);
_eval = _expr.getExpr();
}
/**
* Constructor for Expression, using a custom regex engine to compile any
* regex literals or dynamic string patterns encountered (e.g. for
* $match/$replace/$split) instead of the default
* {@link java.util.regex.Pattern}-backed one.
*
* @param expression
* the logic to be parsed for later execution via evaluate
* methods
* @param regexEngine
* the regex engine to use
* @throws ParseException
* @throws IOException
*/
public Expression(String expression, RegexEngine regexEngine) throws ParseException, IOException {
_regexEngine = regexEngine != null ? regexEngine : RegexEngine.defaultEngine();
_expr = Expressions.parse(expression, _regexEngine);
_eval = _expr.getExpr();
}
/**
* Assign the binding to the environment preparing for evaluation
*
* @param binding
*/
public void assign(Binding binding) {
if (binding.getType() == BindingType.VARIABLE) {
_variableMap.put(binding.getVarName(), binding.getExpression());
} else {
_declaredFunctionMap.put(binding.getVarName(), binding.getFunction());
}
}
/**
* Assign the expression (variable or function declaration) to the variable name
* supplied
*
* @param varname
* name of the variable to map to a variable expression or
* function declaration expression
* @param expression
* logic to be assigned to the variable name
* @throws ParseException
* @throws IOException
*/
public void assign(String varname, String expression) throws ParseException, IOException {
Binding binding = new Binding(varname, expression);
assign(binding);
}
/**
* Remove all bindings
*/
public void clear() {
_variableMap.clear();
_declaredFunctionMap.clear();
}
/**
* Generate a result form the Expression's parsed expression and variable
* assignments or registered functions
*
* @param rootContext
* JSON object specifying the content used to evaluate the
* expression
* @return the result from executing the Expression's parsed expression and
* variable assignments or registered functions. A null will be returned
* if no match is found (note a JSON null will result in a JsonNode of
* type NullNode).
* @throws ParseException
*/
public JsonNode evaluate(JsonNode rootContext) throws ParseException {
ExpressionsVisitor eval = new ExpressionsVisitor(rootContext, new FrameEnvironment(null), _regexEngine);
// process any stored bindings
for (Iterator<String> it = _variableMap.keySet().iterator(); it.hasNext();) {
String key = it.next();
ExprContext ctx = _variableMap.get(key);
eval.setVariable(key, eval.visit(ctx));
}
for (Iterator<String> it = _declaredFunctionMap.keySet().iterator(); it.hasNext();) {
String key = it.next();
DeclaredFunction fct = _declaredFunctionMap.get(key);
eval.setDeclaredFunction(key, fct);
}
return eval.visit(_expr.getTree());
}
/**
* Generate a result form the Expression's parsed expression and variable
* assignments or registered functions specified in the bindings object
*
* @param rootContext
* JSON object specifying the content used to evaluate the
* expression
* @param bindingObj
* a JSON object containing the assignments of variable names
* to variable expressions or function declarations
* @return the result from executing the Expression's parsed expression and
* variable assignments or registered functions specified in the
* bindings object
* @throws ParseException
* @throws IOException
*/
public JsonNode evaluate(JsonNode rootContext, JsonNode bindingObj) throws ParseException, IOException {
return evaluate(rootContext, createBindings(bindingObj));
}
/**
* Generate a result form the Expression's parsed expression and variable
* assignments or registered functions specified in the bindings object
*
* @param rootContext
* JSON object specifying the content used to evaluate the
* expression
* @param bindingObj
* a JSON object containing the assignments of variable names
* to variable expressions or function declarations
* @param timeoutMS
* milliseconds allowed for the evaluation to occur. If it
* takes longer an exception is thrown. Must be positive
* number or exception is thrown.
* @param maxDepth
* the maximum call stack depth allowed before an exception
* is thrown. Must be a positive number or an exception is
* thrown.
* @return the result from executing the Expression's parsed expression and
* variable assignments or registered functions specified in the
* bindings object
* @throws ParseException
* @throws IOException
* @throws EvaluateException
*/
public JsonNode evaluate(JsonNode rootContext, JsonNode bindingObj, long timeoutMS, int maxDepth)
throws ParseException, IOException, EvaluateException {
return evaluate(rootContext, createBindings(bindingObj), timeoutMS, maxDepth);
}
/**
* Generate a result form the Expression's parsed expression and variable
* assignments or registered functions specified in the list of bindings
*
* @param rootContext
* JSON object specifying the content used to evaluate the
* expression
* @param bindings
* assignments of variable names to variable expressions or
* function declarations
* @return the result from executing the Expression's parsed expression and
* variable assignments or registered functions specified in the list of
* bindings. A null will be returned if no match is found (note a JSON
* null will result in a JsonNode of type NullNode).
* @throws ParseException
*/
public JsonNode evaluate(JsonNode rootContext, List<Binding> bindings) throws ParseException {
JsonNode result = null;
// first do variables
for (Binding binding : bindings) {
assign(binding);
}
result = evaluate(rootContext);
return result;
}
/**
* Generate a result form the Expression's parsed expression and variable
* assignments or registered functions specified in the list of bindings
*
* @param rootContext
* JSON object specifying the content used to evaluate the
* expression
* @param bindings
* assignments of variable names to variable expressions or
* function declarations
* @param timeoutMS
* milliseconds allowed for the evaluation to occur. If it
* takes longer an exception is thrown. Must be positive
* number or exception is thrown.
* @param maxDepth
* the maximum call stack depth allowed before an exception
* is thrown. Must be a positive number or an exception is
* thrown.
* @return the result from executing the Expression's parsed expression and
* variable assignments or registered functions specified in the list of
* bindings. A null will be returned if no match is found (note a JSON
* null will result in a JsonNode of type NullNode).
* @throws ParseException
* @throws EvaluateException
*/
public JsonNode evaluate(JsonNode rootContext, List<Binding> bindings, long timeoutMS, int maxDepth)
throws ParseException, EvaluateException {
JsonNode result = null;
// first do variables
for (Binding binding : bindings) {
assign(binding);
}
result = evaluate(rootContext, timeoutMS, maxDepth);
return result;
}
/**
* Generate a result form the Expression's parsed expression and variable
* assignments or registered functions
*
* @param rootContext
* JSON object specifying the content used to evaluate the
* expression
* @param timeoutMS
* milliseconds allowed for the evaluation to occur. If it
* takes longer an exception is thrown. Must be positive
* number or exception is thrown.
* @param maxDepth
* the maximum call stack depth allowed before an exception
* is thrown. Must be a positive number or an exception is
* thrown.
* @return the JsonNode resulting from the expression evaluation against the
* rootContext. A null will be returned if no match is found (note a
* JSON null will result in a JsonNode of type NullNode).
* @throws EvaluateException
* If the given device event is invalid.
*/
public JsonNode evaluate(JsonNode rootContext, long timeoutMS, int maxDepth) throws EvaluateException {
ExpressionsVisitor eval = new ExpressionsVisitor(rootContext, new FrameEnvironment(null), _regexEngine);
// process any stored bindings
for (Iterator<String> it = _variableMap.keySet().iterator(); it.hasNext();) {
String key = it.next();
ExprContext ctx = _variableMap.get(key);
eval.setVariable(key, eval.visit(ctx));
}
for (Iterator<String> it = _declaredFunctionMap.keySet().iterator(); it.hasNext();) {
String key = it.next();
DeclaredFunction fct = _declaredFunctionMap.get(key);
eval.setDeclaredFunction(key, fct);
}
eval.timeboxExpression(timeoutMS, maxDepth);
return eval.visit(_expr.getTree());
}
/**
* Generate a result form the Expression's parsed expression and variable
* assignments or registered functions. This method is synchronized to enable
* multi-threaded execution.
*
* @param rootContext
* JSON object specifying the content used to evaluate the
* expression
* @return the result from executing the Expression's parsed expression and
* variable assignments or registered functions. A null will be returned
* if no match is found (note a JSON null will result in a JsonNode of
* type NullNode).
* @throws ParseException
*/
public synchronized JsonNode evaluateSynced(JsonNode rootContext) throws ParseException {
return evaluate(rootContext);
}
/**
* Generate a result form the Expression's parsed expression and variable
* assignments or registered functions specified in the bindings object
*
* @param rootContext
* JSON object specifying the content used to evaluate the
* expression
* @param bindingObj
* a JSON object containing the assignments of variable names
* to variable expressions or function declarations
* @return the result from executing the Expression's parsed expression and
* variable assignments or registered functions specified in the
* bindings object
* @throws ParseException
* @throws IOException
*/
public synchronized JsonNode evaluateSynced(JsonNode rootContext, JsonNode bindingObj)
throws ParseException, IOException {
return evaluate(rootContext, bindingObj);
}
/**
* Generate a result form the Expression's parsed expression and variable
* assignments or registered functions specified in the bindings object. This
* method is synchronized to enable multi-threaded execution.
*
* @param rootContext
* JSON object specifying the content used to evaluate the
* expression
* @param bindingObj
* a JSON object containing the assignments of variable names
* to variable expressions or function declarations
* @param timeoutMS
* milliseconds allowed for the evaluation to occur. If it
* takes longer an exception is thrown. Must be positive
* number or exception is thrown.
* @param maxDepth
* the maximum call stack depth allowed before an exception
* is thrown. Must be a positive number or an exception is
* thrown.
* @return the result from executing the Expression's parsed expression and
* variable assignments or registered functions specified in the
* bindings object
* @throws ParseException
* @throws IOException
* @throws EvaluateException
*/
public synchronized JsonNode evaluateSynced(JsonNode rootContext, JsonNode bindingObj, long timeoutMS, int maxDepth)
throws ParseException, IOException, EvaluateException {
return evaluate(rootContext, createBindings(bindingObj), timeoutMS, maxDepth);
}
/**
* Generate a result form the Expression's parsed expression and variable
* assignments or registered functions specified in the list of bindings. This
* method is synchronized to enable multi-threaded execution.
*
* @param rootContext
* JSON object specifying the content used to evaluate the
* expression
* @param bindings
* assignments of variable names to variable expressions or
* function declarations
* @return the result from executing the Expression's parsed expression and
* variable assignments or registered functions specified in the list of
* bindings. A null will be returned if no match is found (note a JSON
* null will result in a JsonNode of type NullNode).
* @throws ParseException
*/
public synchronized JsonNode evaluateSynced(JsonNode rootContext, List<Binding> bindings) throws ParseException {
return evaluate(rootContext, bindings);
}
/**
* Generate a result form the Expression's parsed expression and variable
* assignments or registered functions specified in the list of bindings. This
* method is synchronized to enable multi-threaded execution.
*
* @param rootContext
* JSON object specifying the content used to evaluate the
* expression
* @param bindings
* assignments of variable names to variable expressions or
* function declarations
* @param timeoutMS
* milliseconds allowed for the evaluation to occur. If it
* takes longer an exception is thrown. Must be positive
* number or exception is thrown.
* @param maxDepth
* the maximum call stack depth allowed before an exception
* is thrown. Must be a positive number or an exception is
* thrown.
* @return the result from executing the Expression's parsed expression and
* variable assignments or registered functions specified in the list of
* bindings. A null will be returned if no match is found (note a JSON
* null will result in a JsonNode of type NullNode).
* @throws ParseException
* @throws EvaluateException
*/
public synchronized JsonNode evaluateSynced(JsonNode rootContext, List<Binding> bindings, long timeoutMS,
int maxDepth) throws ParseException, EvaluateException {
return evaluate(rootContext, bindings, timeoutMS, maxDepth);
}
/**
* Generate a result form the Expression's parsed expression and variable
* assignments or registered functions. This method is synchronized to enable
* multi-threaded execution.
*
* @param rootContext
* JSON object specifying the content used to evaluate the
* expression
* @param timeoutMS
* milliseconds allowed for the evaluation to occur. If it
* takes longer an exception is thrown. Must be positive
* number or exception is thrown.
* @param maxDepth
* the maximum call stack depth allowed before an exception
* is thrown. Must be a positive number or an exception is
* thrown.
* @return the JsonNode resulting from the expression evaluation against the
* rootContext. A null will be returned if no match is found (note a
* JSON null will result in a JsonNode of type NullNode).
* @throws EvaluateException
* If the given device event is invalid.
*/
public synchronized JsonNode evaluateSynced(JsonNode rootContext, long timeoutMS, int maxDepth)
throws EvaluateException {
return evaluate(rootContext, timeoutMS, maxDepth);
}
/**
* Registers a function implementation (declaration) by name
*
* @param fctName
* the name of the function
* @param implementation
* the function declaration
* @throws ParseException
* @throws IOException
*/
public void registerFunction(String fctName, String implementation) throws ParseException, IOException {
Binding fctBinding = new Binding(fctName, implementation);
_declaredFunctionMap.put(fctBinding.getVarName(), fctBinding.getFunction());
}
}