Repository navigation
Expand file tree
/
Copy pathMatchFunction.java
More file actions
240 lines (225 loc) · 10.9 KB
/
Copy pathMatchFunction.java
File metadata and controls
240 lines (225 loc) · 10.9 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
/**
* (c) Copyright 2018, 2019 IBM Corporation
* 1 New Orchard Road,
* Armonk, New York, 10504-1722
* United States
* +1 914 499 1900
* support: Nathaniel Mills wnm3@us.ibm.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.api.jsonata4java.expressions.functions;
import java.util.Optional;
import java.util.regex.Pattern;
import com.api.jsonata4java.expressions.EvaluateRuntimeException;
import com.api.jsonata4java.expressions.ExpressionsVisitor;
import com.api.jsonata4java.expressions.ExpressionsVisitor.SelectorArrayNode;
import com.api.jsonata4java.expressions.RegularExpression;
import com.api.jsonata4java.expressions.generated.MappingExpressionParser.ExprContext;
import com.api.jsonata4java.expressions.generated.MappingExpressionParser.Function_callContext;
import com.api.jsonata4java.expressions.regex.JdkRegexPattern;
import com.api.jsonata4java.expressions.regex.RegexFlags;
import com.api.jsonata4java.expressions.regex.RegexMatch;
import com.api.jsonata4java.expressions.regex.RegexPattern;
import com.api.jsonata4java.expressions.utils.Constants;
import com.api.jsonata4java.expressions.utils.FunctionUtils;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.node.ArrayNode;
import tools.jackson.databind.node.JsonNodeFactory;
import tools.jackson.databind.node.ObjectNode;
import tools.jackson.databind.node.POJONode;
/**
* From http://docs.jsonata.org/string-functions.html:
*
* $match(str, pattern [, limit])
*
* Finds occurrences of pattern within str and reports them with their index and
* group.
*
* If str is not specified, then the context value is used as the value of str.
* It is an error if str is not a string.
*
* The pattern parameter must be a regular expression (regex) String used for
* searching the string.
*
* The optional limit parameter, is a number that specifies the maximum number
* of results to be found before stopping.
*
* Examples
*
* $match("John Smith and John Jones", "John") ==
* "[{"match":"John","index":0,"groups":["John"]},{"match":"John","index":15,"groups":["John"]}]
*
*/
public class MatchFunction extends FunctionBase {
public static String ERR_BAD_CONTEXT = String.format(Constants.ERR_MSG_BAD_CONTEXT, Constants.FUNCTION_MATCH);
public static String ERR_ARG1BADTYPE = String.format(Constants.ERR_MSG_ARG1_BAD_TYPE, Constants.FUNCTION_MATCH);
public static String ERR_ARG2BADTYPE = String.format(Constants.ERR_MSG_ARG2_BAD_TYPE, Constants.FUNCTION_MATCH);
public static String ERR_ARG3BADTYPE = String.format(Constants.ERR_MSG_ARG3_BAD_TYPE, Constants.FUNCTION_MATCH);
public static String ERR_ARG4BADTYPE = String.format(Constants.ERR_MSG_ARG4_BAD_TYPE, Constants.FUNCTION_MATCH);
public JsonNode invoke(ExpressionsVisitor expressionVisitor, Function_callContext ctx) {
// Create the variable to return
SelectorArrayNode result = null;
// Retrieve the number of arguments
JsonNode argString = JsonNodeFactory.instance.nullNode();
boolean useContext = FunctionUtils.useContextVariable(this, ctx, getSignature());
int argCount = getArgumentCount(ctx);
if (useContext) {
argString = FunctionUtils.getContextVariable(expressionVisitor);
if (argString != null && argString.isNull() == false) {
argCount++;
} else {
useContext = false;
}
}
// Make sure that we have the right number of arguments
if (argCount == 2 || argCount == 3) {
if (!useContext) {
argString = FunctionUtils.getValuesListExpression(expressionVisitor, ctx, 0);
}
final JsonNode argPattern = FunctionUtils.getValuesListExpression(expressionVisitor, ctx,
useContext ? 0 : 1);
int limit = -1;
// As in jsonata-js, an undefined str with a regex pattern returns undefined
if (argString == null && argPattern instanceof POJONode) {
if (argCount == 3) {
final JsonNode argLimit = FunctionUtils.getValuesListExpression(expressionVisitor, ctx, useContext ? 1 : 2);
if (argLimit != null && !argLimit.isNumber()) {
throw new EvaluateRuntimeException(ERR_ARG3BADTYPE);
}
}
return null;
}
// Make sure that we have the right number of arguments
if (argString == null || !argString.isTextual()) {
throw new EvaluateRuntimeException(ERR_ARG1BADTYPE);
}
// Make sure that the pattern is a non-empty string.
// The emptiness check is guarded by isTextual() because a POJONode
// wraps a compiled RegularExpression (inherently non-empty): under
// Jackson 2 asText() returned the POJO's toString(), but Jackson 3's
// asText()/asString() throws for a POJONode. Skipping the check for
// non-textual nodes keeps the original behavior without that throw.
if (argPattern != null && (argPattern.isTextual() || argPattern instanceof POJONode) && !(argPattern.isTextual() && argPattern.asText().isEmpty())) {
RegularExpression regex = null;
if (argPattern instanceof POJONode) {
regex = (RegularExpression) ((POJONode) argPattern).getPojo();
}
final RegexPattern regexPattern;
if (regex != null) {
regexPattern = regex.getPattern();
} else {
// A plain-string pattern is treated as an exact literal to
// search for, not as a user-authored regex, so this
// intentionally always uses the default engine's quoting
// rather than routing through a pluggable RegexEngine
// (whose escaping dialect may not understand
// Pattern.quote()'s \Q...\E syntax).
regexPattern = new JdkRegexPattern(Pattern.quote(argPattern.textValue()), new RegexFlags(false, false));
}
// Check to see if the separator is just a string
final String str = argString.textValue();
if (argCount == 3) {
final JsonNode argLimit = FunctionUtils.getValuesListExpression(expressionVisitor, ctx, useContext ? 1 : 2);
// Check to see if we have an optional limit argument we check it
if (argLimit != null) {
if (argLimit.isNumber() && argLimit.asInt() >= 0) {
limit = argLimit.asInt();
} else {
throw new EvaluateRuntimeException(ERR_ARG3BADTYPE);
}
}
}
// Check to see if a limit was specified
result = new SelectorArrayNode(JsonNodeFactory.instance);
if (limit == -1) {
// No limit... match all occurrences in the string
for (final RegexMatch m : regexPattern.findAll(str)) {
result.add(toMatchObject(m));
}
} else if (limit > 0) {
// Stream matches one at a time so we can stop as soon as the
// limit is reached, instead of scanning the whole string.
int count = 0;
int pos = 0;
while (count < limit) {
final Optional<RegexMatch> found = regexPattern.findFirst(str, pos);
if (!found.isPresent()) {
break;
}
final RegexMatch m = found.get();
result.add(toMatchObject(m));
count++;
pos = m.getIndex() + Math.max(m.getLength(), 1);
}
} else {
return null;
}
// As in jsonata-js, no match returns undefined
if (result.size() == 0) {
return null;
}
} else {
// check for a function call context as 2nd parameter
ExprContext exprCtx = ctx.exprValues().exprList().expr(useContext ? 0 : 1);
if (exprCtx instanceof Function_callContext) {
// try for declared then jsonata
Function_callContext fctCallCtx = (Function_callContext) exprCtx;
String fctName = fctCallCtx.VAR_ID().getText();
DeclaredFunction declFct = expressionVisitor.getDeclaredFunction(fctName);
if (declFct == null) {
FunctionBase function = expressionVisitor.getJsonataFunction(fctName);
if (function != null) {
result = (SelectorArrayNode) function.invoke(expressionVisitor, fctCallCtx);
} else {
throw new EvaluateRuntimeException("Unknown function: " + fctName);
}
} else {
result = (SelectorArrayNode) declFct.invoke(expressionVisitor, fctCallCtx);
}
} else {
throw new EvaluateRuntimeException(ERR_ARG2BADTYPE);
}
}
} else {
throw new EvaluateRuntimeException(argCount <= 1 ? ERR_ARG1BADTYPE : ERR_ARG4BADTYPE);
}
return result;
}
private static ObjectNode toMatchObject(RegexMatch m) {
final ObjectNode obj = JsonNodeFactory.instance.objectNode();
obj.put("match", m.getMatch());
obj.put("index", Long.valueOf(m.getIndex()));
final ArrayNode groups = JsonNodeFactory.instance.arrayNode();
obj.set("groups", groups);
for (final String group : m.getGroups()) {
groups.add(group);
}
return obj;
}
@Override
public int getMaxArgs() {
return 3;
}
@Override
public int getMinArgs() {
return 1; // account for context variable
}
@Override
public String getSignature() {
// accepts a string (or context variable), a function (that accepts a string and
// returns an object), an optional number, returns an array of objects
return "<s-f<s:o>n?:a<o>>";
}
}