Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/main/java/com/dashjoin/jsonata/Functions.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
// }, "<s?s?:s>"));
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;
}

Expand Down
44 changes: 29 additions & 15 deletions src/main/java/com/dashjoin/jsonata/Jsonata.java
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ public Frame(Frame enclosingEnvironment) {
parent = enclosingEnvironment;
if (enclosingEnvironment!=null) {
base = enclosingEnvironment.base;
// timestamp: enclosingEnvironment ? enclosingEnvironment.timestamp : null,
time = enclosingEnvironment.time;
}
}

Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -402,7 +404,7 @@ Frame createFrameFromTuple(Frame environment, Map<String, Object> 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) {
Expand Down Expand Up @@ -435,7 +437,7 @@ Frame createFrameFromTuple(Frame environment, Map<String, Object> 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++) {
Expand Down Expand Up @@ -490,7 +492,7 @@ Frame createFrameFromTuple(Frame environment, Map<String, Object> 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;
Expand Down Expand Up @@ -532,9 +534,10 @@ Frame createFrameFromTuple(Frame environment, Map<String, Object> 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) {
Expand Down Expand Up @@ -562,6 +565,9 @@ Frame createFrameFromTuple(Frame environment, Map<String, Object> 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;
Expand All @@ -573,6 +579,8 @@ Frame createFrameFromTuple(Frame environment, Map<String, Object> 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)) {
Expand All @@ -582,6 +590,10 @@ Frame createFrameFromTuple(Frame environment, Map<String, Object> 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);
}
Expand All @@ -590,6 +602,12 @@ Frame createFrameFromTuple(Frame environment, Map<String, Object> 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;
}
Expand Down Expand Up @@ -2571,7 +2589,6 @@ Exception populateMessage(Exception err) {
List<Exception> errors;
Frame environment;
Symbol ast;
long timestamp;
Object input;

static {
Expand Down Expand Up @@ -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);
// }, "<s?s?:s>"));
// environment.bind("millis", defineFunction(function() {
// return timestamp.getTime();
// return this.environment.timestamp.getTime();
// }, "<:n>"));

// FIXED: options.RegexEngine not implemented in Java
Expand All @@ -2656,7 +2671,6 @@ public static class OptionsBuilder {
Jsonata(Jsonata other) {
this.ast = other.ast;
this.environment = other.environment;
this.timestamp = other.timestamp;
}

/**
Expand Down Expand Up @@ -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
Expand Down
63 changes: 63 additions & 0 deletions src/test/java/com/dashjoin/jsonata/ThreadSafetyTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<Long, Object>) millis -> {
secondMillis[0] = millis;
return null;
});

long[] firstMillis = new long[1];
Jsonata.Frame env1 = expr.createFrame();
env1.bind("pause", (Jsonata.Fn1<Long, Object>) 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();
}
}
}
30 changes: 30 additions & 0 deletions test/test-overrides.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
]
}
Loading