diff --git a/jsonata b/jsonata index 6c7e95f..6d9d829 160000 --- a/jsonata +++ b/jsonata @@ -1 +1 @@ -Subproject commit 6c7e95fdbf4405a1e741852a7cd8cd985b4305bb +Subproject commit 6d9d8290c1c084fb73499e40c73813f7929ee98d diff --git a/src/main/java/com/dashjoin/jsonata/Functions.java b/src/main/java/com/dashjoin/jsonata/Functions.java index e2f94e8..7ee48b6 100644 --- a/src/main/java/com/dashjoin/jsonata/Functions.java +++ b/src/main/java/com/dashjoin/jsonata/Functions.java @@ -2445,18 +2445,18 @@ public static Object functionEval(String expr, Object focus) { } // environment.bind("now", defineFunction(function(picture, timezone) { - // return datetime.fromMillis(timestamp.getTime(), picture, timezone); + // return datetime.fromMillis(this.environment.timestamp.getTime(), picture, timezone); // }, "")); public static String now(String picture, String timezone) { - long t = Jsonata.current.get().timestamp; + long t = Jsonata.current.get().environment.time; return dateTimeFromMillis(t, picture, timezone); } // environment.bind("millis", defineFunction(function() { - // return timestamp.getTime(); + // return this.environment.timestamp.getTime(); // }, "<:n>")); public static long millis() { - long t = Jsonata.current.get().timestamp; + long t = Jsonata.current.get().environment.time; return t; } diff --git a/src/main/java/com/dashjoin/jsonata/Jsonata.java b/src/main/java/com/dashjoin/jsonata/Jsonata.java index c5a0277..fa40e57 100644 --- a/src/main/java/com/dashjoin/jsonata/Jsonata.java +++ b/src/main/java/com/dashjoin/jsonata/Jsonata.java @@ -78,6 +78,8 @@ public Frame(Frame enclosingEnvironment) { parent = enclosingEnvironment; if (enclosingEnvironment!=null) { base = enclosingEnvironment.base; + // timestamp: enclosingEnvironment ? enclosingEnvironment.timestamp : null, + time = enclosingEnvironment.time; } } @@ -256,7 +258,7 @@ Object _evaluate(Symbol expr, Object input, Frame environment) { if (expr.predicate!=null) for(var ii = 0; ii < expr.predicate.size(); ii++) { - result = /* await */ evaluateFilter(expr.predicate.get(ii).expr, result, environment); + result = /* await */ evaluateFilter(expr.predicate.get(ii).expr, result, environment, ii < expr.predicate.size() - 1); } if (!expr.type.equals("path") && expr.group!=null) { @@ -402,7 +404,7 @@ Frame createFrameFromTuple(Frame environment, Map tuple) { var res = /* await */ evaluate(expr, ((List)input).get(ii), environment); if(expr.stages!=null) { for(var ss = 0; ss < expr.stages.size(); ss++) { - res = /* await */ evaluateFilter(expr.stages.get(ss).expr, res, environment); + res = /* await */ evaluateFilter(expr.stages.get(ss).expr, res, environment, ss < expr.stages.size() - 1); } } if(res != null) { @@ -435,7 +437,7 @@ Frame createFrameFromTuple(Frame environment, Map tuple) { var stage = stages.get(ss); switch(stage.type) { case "filter": - result = /* await */ evaluateFilter(stage.expr, result, environment); + result = /* await */ evaluateFilter(stage.expr, result, environment, ss < stages.size() - 1 && stages.get(ss + 1).type.equals("filter")); break; case "index": for(var ee = 0; ee < ((List)result).size(); ee++) { @@ -490,7 +492,7 @@ Frame createFrameFromTuple(Frame environment, Map tuple) { // res is the binding sequence for the output tuple stream if (_res!=null) { //(typeof res !== "undefined") { List res; - if (!(_res instanceof List)) { + if (!(_res instanceof List) || (_res instanceof JList && ((JList)_res).cons && expr.stages == null)) { res = new ArrayList<>(); res.add(_res); } else { res = (List)_res; @@ -532,9 +534,10 @@ Frame createFrameFromTuple(Frame environment, Map tuple) { * @param {Object} predicate - filter expression * @param {Object} input - Input data to apply predicates against * @param {Object} environment - Environment + * @param {boolean} chained - another predicate will be applied to the result * @returns {*} Result after applying predicates */ - /* async */ Object evaluateFilter(Object _predicate, Object input, Frame environment) { + /* async */ Object evaluateFilter(Object _predicate, Object input, Frame environment, boolean chained) { Symbol predicate = (Symbol)_predicate; var results = environment.base.createSequence(); if( input instanceof JList && ((JList)input).tupleStream) { @@ -562,6 +565,9 @@ Frame createFrameFromTuple(Frame environment, Map tuple) { } } } else { + // the position selected by the predicate, while it evaluates to the same number for every item + Integer position = null; + var samePosition = true; for (int index = 0; index < ((List)input).size(); index++) { var item = ((List)input).get(index); var context = item; @@ -573,6 +579,8 @@ Frame createFrameFromTuple(Frame environment, Map tuple) { var res = /* await */ evaluate(predicate, context, env); if (Utils.isNumeric(res)) { res = environment.base.createSequence(res); + } else { + samePosition = false; } if (Utils.isArrayOfNumbers(res)) { for (Object ires : ((List)res)) { @@ -582,6 +590,10 @@ Frame createFrameFromTuple(Frame environment, Map tuple) { // count in from end of array ii = ((List)input).size() + ii; } + if (index > 0 && (position == null || ii != position)) { + samePosition = false; + } + position = ii; if (ii == index) { results.add(item); } @@ -590,6 +602,12 @@ Frame createFrameFromTuple(Frame environment, Map tuple) { results.add(item); } } + if (chained && samePosition && results.size() == 1 && results.get(0) instanceof List) { + // an expression that evaluates to the same number for every item selects an array the same way + // a literal index does, so the next predicate is applied to that array rather than to a sequence + // containing it + results = (List)results.get(0); + } } return results; } @@ -2571,7 +2589,6 @@ Exception populateMessage(Exception err) { List errors; Frame environment; Symbol ast; - long timestamp; Object input; static { @@ -2626,14 +2643,12 @@ public static class OptionsBuilder { } environment = createFrame(staticFrame); - timestamp = System.currentTimeMillis(); // will be overridden on each call to evalute() - // Note: now and millis are implemented in Functions // environment.bind("now", defineFunction(function(picture, timezone) { - // return datetime.fromMillis(timestamp.getTime(), picture, timezone); + // return datetime.fromMillis(this.environment.timestamp.getTime(), picture, timezone); // }, "")); // environment.bind("millis", defineFunction(function() { - // return timestamp.getTime(); + // return this.environment.timestamp.getTime(); // }, "<:n>")); // FIXED: options.RegexEngine not implemented in Java @@ -2656,7 +2671,6 @@ public static class OptionsBuilder { Jsonata(Jsonata other) { this.ast = other.ast; this.environment = other.environment; - this.timestamp = other.timestamp; } /** @@ -2729,16 +2743,16 @@ public Object evaluate(Object input, Frame bindings) { // FIXME:, callback) { exec_env.bind(v, bindings.lookup(v)); } } else { - exec_env = environment; + // Java: always use a per evaluation frame, so that concurrent evaluations + // of the same expression do not overwrite each other's timestamp + exec_env = createFrame(environment); } // put the input document into the environment as the root object exec_env.bind("$", input); // capture the timestamp and put it in the execution environment // the $now() and $millis() functions will return this value - whenever it is called - timestamp = System.currentTimeMillis(); - //exec_env.timestamp = timestamp; - exec_env.time = timestamp; + exec_env.time = System.currentTimeMillis(); // exec_env.timestamp = new Date(); exec_env.options = options; // if the input is a JSON array, then wrap it in a singleton sequence so it gets treated as a single input diff --git a/src/test/java/com/dashjoin/jsonata/ThreadSafetyTest.java b/src/test/java/com/dashjoin/jsonata/ThreadSafetyTest.java index bec51de..cc2f046 100644 --- a/src/test/java/com/dashjoin/jsonata/ThreadSafetyTest.java +++ b/src/test/java/com/dashjoin/jsonata/ThreadSafetyTest.java @@ -293,4 +293,67 @@ public void testMillisWithCachedInstance() throws Exception { assertTrue(r2 > r1, "$millis() should advance across separate evaluations"); } + + /** + * Port of upstream test for https://github.com/jsonata-js/jsonata/commit/c5be11676cf038b048a1201069f85f59b504993f + * $millis() and $now() are not affected by an overlapping evaluate() call + */ + @Test + public void testMillisNotAffectedByOverlappingEvaluate() throws Exception { + Jsonata expr = jsonata("($m := $millis(); $n := $now(); $pause($m); [$m = $millis(), $n = $now()])"); + long[] secondMillis = new long[1]; + Object[] second = new Object[1]; + + Jsonata.Frame env2 = expr.createFrame(); + env2.bind("pause", (Jsonata.Fn1) millis -> { + secondMillis[0] = millis; + return null; + }); + + long[] firstMillis = new long[1]; + Jsonata.Frame env1 = expr.createFrame(); + env1.bind("pause", (Jsonata.Fn1) millis -> { + firstMillis[0] = millis; + // make sure the overlapping evaluation captures a later timestamp + while (System.currentTimeMillis() <= millis) { + try { Thread.sleep(1); } catch (InterruptedException e) { throw new RuntimeException(e); } + } + // the first evaluation is suspended here while the second one runs + second[0] = expr.evaluate(null, env2); + return null; + }); + + Object first = expr.evaluate(null, env1); + assertTrue(secondMillis[0] > firstMillis[0]); + assertEquals(Arrays.asList(true, true), second[0]); + assertEquals(Arrays.asList(true, true), first); + } + + @Test + public void testMillisNotAffectedByOtherInstance() throws Exception { + Jsonata exprA = jsonata("$millis()"); + Thread.sleep(2); + // constructing exprB must not make exprA return a stale timestamp + jsonata("$millis()"); + Thread.sleep(2); + long before = System.currentTimeMillis(); + long r = ((Number) exprA.evaluate(null)).longValue(); + assertTrue(r >= before, "$millis() should return the timestamp of the current evaluation"); + } + + @Test + public void testMillisOnOtherThread() throws Exception { + Jsonata expr = jsonata("$millis()"); + expr.evaluate(null); + ExecutorService pool = Executors.newSingleThreadExecutor(); + try { + pool.submit(() -> expr.evaluate(null)).get(); + Thread.sleep(2); + long before = System.currentTimeMillis(); + long r = ((Number) pool.submit(() -> expr.evaluate(null)).get()).longValue(); + assertTrue(r >= before, "$millis() should return the timestamp of the current evaluation"); + } finally { + pool.shutdown(); + } + } } diff --git a/test/test-overrides.json b/test/test-overrides.json index 4c24ee4..013f1df 100644 --- a/test/test-overrides.json +++ b/test/test-overrides.json @@ -144,6 +144,36 @@ "name": "regex/case022.json", "ignoreError": true, "reason": "Java regexp OK with this case. Jsonata regexp throws error because the regexp matches 0 characters, which could cause an endless loop in the custom matcher." + }, + { + "name": "function-formatNumber/issue851.json_0", + "ignoreError": true, + "reason": "formatNumber irregular grouping (e.g. '#,##,##0') not implemented, java.text.DecimalFormat only supports regular grouping. See https://github.com/jsonata-js/jsonata/commit/67c36a50fdd9da20fb4ee7c25c8aaca213f23720" + }, + { + "name": "function-formatNumber/issue851.json_1", + "ignoreError": true, + "reason": "formatNumber irregular grouping (e.g. '#,##,##0') not implemented, java.text.DecimalFormat only supports regular grouping. See https://github.com/jsonata-js/jsonata/commit/67c36a50fdd9da20fb4ee7c25c8aaca213f23720" + }, + { + "name": "function-formatNumber/issue851.json_2", + "ignoreError": true, + "reason": "formatNumber irregular grouping (e.g. '#,##,##0') not implemented, java.text.DecimalFormat only supports regular grouping. See https://github.com/jsonata-js/jsonata/commit/67c36a50fdd9da20fb4ee7c25c8aaca213f23720" + }, + { + "name": "function-formatNumber/issue851.json_3", + "ignoreError": true, + "reason": "formatNumber irregular grouping (e.g. '#,##,##0') not implemented, java.text.DecimalFormat only supports regular grouping. See https://github.com/jsonata-js/jsonata/commit/67c36a50fdd9da20fb4ee7c25c8aaca213f23720" + }, + { + "name": "function-formatNumber/issue851.json_4", + "ignoreError": true, + "reason": "formatNumber irregular grouping (e.g. '#,##,##0') not implemented, java.text.DecimalFormat only supports regular grouping. See https://github.com/jsonata-js/jsonata/commit/67c36a50fdd9da20fb4ee7c25c8aaca213f23720" + }, + { + "name": "function-formatNumber/issue851.json_6", + "ignoreError": true, + "reason": "formatNumber irregular grouping (e.g. '#,##,##0') not implemented, java.text.DecimalFormat only supports regular grouping. See https://github.com/jsonata-js/jsonata/commit/67c36a50fdd9da20fb4ee7c25c8aaca213f23720" } ] }