forked from dashjoin/jsonata-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctions.java
More file actions
2426 lines (2119 loc) · 77 KB
/
Functions.java
File metadata and controls
2426 lines (2119 loc) · 77 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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* jsonata-java is the JSONata Java reference port
*
* Copyright Dashjoin GmbH. https://dashjoin.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.dashjoin.jsonata;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.OptionalDouble;
import java.util.Set;
import java.util.TimeZone;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.dashjoin.jsonata.Jsonata.jsonata;
import com.dashjoin.jsonata.Jsonata.JFunction;
import com.dashjoin.jsonata.Parser.Symbol;
import com.dashjoin.jsonata.Utils.JList;
import com.dashjoin.jsonata.json.Json;
import com.dashjoin.jsonata.utils.Constants;
import com.dashjoin.jsonata.utils.DateTimeUtils;
@SuppressWarnings({"rawtypes", "unchecked"})
public class Functions {
/**
* Sum function
* @param {Object} args - Arguments
* @returns {number} Total value of arguments
*/
public static Number sum(List<Number> args) {
// undefined inputs always return undefined
if (args == null) {
return null;
}
double total = args.stream().mapToDouble(Number::doubleValue).sum();
return total;
}
/**
* Count function
* @param {Object} args - Arguments
* @returns {number} Number of elements in the array
*/
public static Number count(List<Object> args) {
// undefined inputs always return undefined
if (args == null) {
return 0;
}
return args.size();
}
/**
* Max function
* @param {Object} args - Arguments
* @returns {number} Max element in the array
*/
public static Number max(List<Number> args) {
// undefined inputs always return undefined
if (args == null || args.size() == 0) {
return null;
}
OptionalDouble res = args.stream().mapToDouble(Number::doubleValue).max();
if (res.isPresent())
return res.getAsDouble();
else
return null;
}
/**
* Min function
* @param {Object} args - Arguments
* @returns {number} Min element in the array
*/
public static Number min(List<Number> args) {
// undefined inputs always return undefined
if (args == null || args.size() == 0) {
return null;
}
OptionalDouble res = args.stream().mapToDouble(Number::doubleValue).min();
if (res.isPresent())
return res.getAsDouble();
else
return null;
}
/**
* Average function
* @param {Object} args - Arguments
* @returns {number} Average element in the array
*/
public static Number average(List<Number> args) {
// undefined inputs always return undefined
if (args == null || args.size() == 0) {
return null;
}
OptionalDouble res = args.stream().mapToDouble(Number::doubleValue).average();
if (res.isPresent())
return res.getAsDouble();
else
return null;
}
/**
* Stringify arguments
* @param {Object} arg - Arguments
* @param {boolean} [prettify] - Pretty print the result
* @returns {String} String from arguments
*/
public static String string(Object arg, Boolean prettify) {
if (arg instanceof JList)
if (((JList)arg).outerWrapper)
arg = ((JList)arg).get(0);
if (arg == null)
return null;
// see https://docs.jsonata.org/string-functions#string: Strings are unchanged
if (arg instanceof String)
return (String) arg;
StringBuilder sb = new StringBuilder();
string(sb, arg, prettify!=null && prettify, "");
return sb.toString();
}
/**
* Internal recursive string function based on StringBuilder.
* Avoids creation of intermediate String objects
*/
static void string(StringBuilder b, Object arg, boolean prettify, String indent) {
// if (arg == null)
// return null;
if (arg==null || arg == Jsonata.NULL_VALUE) {
b.append("null"); return;
}
if (arg instanceof JFunction) {
return;
}
if (arg instanceof Symbol) {
return;
}
if (arg instanceof Double) {
double d = ((Double)arg).doubleValue();
if (d % 1 == 0 && Long.MIN_VALUE < d && d <= Long.MAX_VALUE) {
b.append(Math.round(d)); return;
}
// TODO: this really should be in the jackson serializer
BigDecimal bd = new BigDecimal((Double)arg, new MathContext(15));
String res = bd.stripTrailingZeros().toString();
if (res.indexOf("E+") > 0)
res = res.replace("E+", "e+");
if (res.indexOf("E-") > 0)
res = res.replace("E-", "e-");
b.append(res); return;
}
if (arg instanceof Number || arg instanceof Boolean) {
b.append(arg); return;
}
if (arg instanceof String) {
// quotes within strings must be escaped
Utils.quote((String)arg, b); return;
}
if (arg instanceof Map) {
b.append('{');
if (prettify)
b.append('\n');
for (Entry<String, Object> e : ((Map<String, Object>) arg).entrySet()) {
if (prettify) {
b.append(indent);
b.append(" ");
}
b.append('"');
Utils.quote(e.getKey(), b);
b.append('"');
b.append(':');
if (prettify)
b.append(' ');
final Object v = e.getValue();
if (v instanceof String || v instanceof Symbol
|| v instanceof JFunction) {
b.append('"');
string(b, v, prettify, indent + " ");
b.append('"');
} else
string(b, v, prettify, indent + " ");
b.append(',');
if (prettify)
b.append('\n');
}
if (!((Map) arg).isEmpty())
b.deleteCharAt(b.length() - (prettify ? 2 : 1));
if (prettify)
b.append(indent);
b.append('}');
return;
}
if ((arg instanceof List)) {
if (((List) arg).isEmpty()) {
b.append("[]"); return;
}
b.append('[');
if (prettify)
b.append('\n');
for (Object v : (List) arg) {
if (prettify) {
b.append(indent);
b.append(" ");
}
if (v instanceof String || v instanceof Symbol || v instanceof JFunction) {
b.append('"');
string(b, v, prettify, indent + " ");
b.append('"');
} else
string(b, v, prettify, indent + " ");
b.append(',');
if (prettify)
b.append('\n');
}
if (!((List) arg).isEmpty())
b.deleteCharAt(b.length() - (prettify ? 2 : 1));
if (prettify)
b.append(indent);
b.append(']');
return;
}
// Throw error for unknown types
throw new IllegalArgumentException("Only JSON types (values, Map, List) can be stringified. Unsupported type: "+arg.getClass().getName());
}
/**
* Validate input data types.
* This will make sure that all input data can be processed.
*
* @param arg
* @return
*/
public static void validateInput(Object arg) {
// if (arg == null)
// return null;
if (arg==null || arg == Jsonata.NULL_VALUE) {
return;
}
if (arg instanceof JFunction) {
return;
}
if (arg instanceof Symbol) {
return;
}
if (arg instanceof Double) {
return;
}
if (arg instanceof Number || arg instanceof Boolean) {
return;
}
if (arg instanceof String) {
return;
}
if (arg instanceof Map) {
for (Entry<String, Object> e : ((Map<String, Object>) arg).entrySet()) {
validateInput(e.getKey());
validateInput(e.getValue());
}
return;
}
if ((arg instanceof List)) {
for (Object v : (List) arg) {
validateInput(v);
}
return;
}
// Throw error for unknown types
throw new IllegalArgumentException("Only JSON types (values, Map, List) are allowed as input. Unsupported type: "+
arg.getClass().getCanonicalName());
}
/**
* Create substring based on character number and length
* @param {String} str - String to evaluate
* @param {Integer} start - Character number to start substring
* @param {Integer} [length] - Number of characters in substring
* @returns {string|*} Substring
*/
public static String substring(String str, Number _start, Number _length) {
// undefined inputs always return undefined
if (str == null) {
return null;
}
Integer start = _start!=null ? _start.intValue() : null;
Integer length = _length!=null ? _length.intValue() : null;
// not used: var strArray = stringToArray(str);
var strLength = str.length();
if (strLength + start < 0) {
start = 0;
}
if (length != null) {
if (length <= 0) {
return "";
}
return substr(str, start, length);
}
return substr(str, start, strLength);
}
/**
* Source = Jsonata4Java JSONataUtils.substr
* @param str
* @param start Location at which to begin extracting characters. If a negative
* number is given, it is treated as strLength - start where
* strLength is the length of the string. For example,
* str.substr(-3) is treated as str.substr(str.length - 3)
* @param length The number of characters to extract. If this argument is null,
* all the characters from start to the end of the string are
* extracted.
* @return A new string containing the extracted section of the given string. If
* length is 0 or a negative number, an empty string is returned.
*/
static public String substr(String str, Integer start, Integer length) {
// below has to convert start and length for emojis and unicode
int origLen = str.length();
String strData = Objects.requireNonNull(str).intern();
int strLen = strData.codePointCount(0, strData.length());
if (start >= strLen) {
return "";
}
// If start is negative, substr() uses it as a character index from the
// end of the string; the index of the last character is -1.
start = strData.offsetByCodePoints(0, start >= 0 ? start : ((strLen + start) < 0 ? 0 : strLen + start));
if (start < 0) {
start = 0;
} // If start is negative and abs(start) is larger than the length of the
// string, substr() uses 0 as the start index.
// If length is omitted, substr() extracts characters to the end of the
// string.
if (length == null) {
length = strData.length();
} else if (length < 0) {
// If length is 0 or negative, substr() returns an empty string.
return "";
} else if (length > strData.length()) {
length = strData.length();
}
length = strData.offsetByCodePoints(0, length);
if (start >= 0) {
// If start is positive and is greater than or equal to the length of
// the string, substr() returns an empty string.
if (start >= origLen) {
return "";
}
}
// collect length characters (unless it reaches the end of the string
// first, in which case it will return fewer)
int end = start + length;
if (end > origLen) {
end = origLen;
}
return strData.substring(start, end);
}
/**
* Create substring up until a character
* @param {String} str - String to evaluate
* @param {String} chars - Character to define substring boundary
* @returns {*} Substring
*/
public static String substringBefore(String str, String chars) {
// undefined inputs always return undefined
if (str == null) {
return null;
}
if (chars==null)
return str;
var pos = str.indexOf(chars);
if (pos > -1) {
return str.substring(0, pos);
} else {
return str;
}
}
/**
* Create substring after a character
* @param {String} str - String to evaluate
* @param {String} chars - Character to define substring boundary
* @returns {*} Substring
*/
public static String substringAfter(String str, String chars) {
// undefined inputs always return undefined
if (str == null) {
return null;
}
var pos = str.indexOf(chars);
if (pos > -1) {
return str.substring(pos + chars.length());
} else {
return str;
}
}
/**
* Lowercase a string
* @param {String} str - String to evaluate
* @returns {string} Lowercase string
*/
public static String lowercase(String str) {
// undefined inputs always return undefined
if (str == null) {
return null;
}
return str.toLowerCase();
}
/**
* Uppercase a string
* @param {String} str - String to evaluate
* @returns {string} Uppercase string
*/
public static String uppercase(String str) {
// undefined inputs always return undefined
if (str == null) {
return null;
}
return str.toUpperCase();
}
/**
* length of a string
* @param {String} str - string
* @returns {Number} The number of characters in the string
*/
public static Integer length(String str) {
// undefined inputs always return undefined
if (str == null) {
return null;
}
return str.codePointCount(0, str.length());
}
/**
* Normalize and trim whitespace within a string
* @param {string} str - string to be trimmed
* @returns {string} - trimmed string
*/
public static String trim(String str) {
// undefined inputs always return undefined
if (str == null) {
return null;
}
if (str.isEmpty()) {
return "";
}
// normalize whitespace
var result = str.replaceAll("[ \t\n\r]+", " ");
if (result.charAt(0) == ' ') {
// strip leading space
result = result.substring(1);
}
if (result.isEmpty()) {
return "";
}
if (result.charAt(result.length() - 1) == ' ') {
// strip trailing space
result = result.substring(0, result.length() - 1);
}
return result;
}
/**
* Pad a string to a minimum width by adding characters to the start or end
* @param {string} str - string to be padded
* @param {number} width - the minimum width; +ve pads to the right, -ve pads to the left
* @param {string} [char] - the pad character(s); defaults to ' '
* @returns {string} - padded string
*/
public static String pad(String str, Number _width, String _char) {
// undefined inputs always return undefined
if (str == null) {
return null;
}
if (_char == null || _char.isEmpty()) {
_char = " ";
}
String result;
int width = _width.intValue();
if (width < 0) {
result = leftPad(str, -width, _char);
} else {
result = rightPad(str, width, _char);
}
return result;
}
// Source: Jsonata4Java PadFunction
public static String leftPad(final String str, final int size, String padStr) {
if (str == null) {
return null;
}
if (padStr == null) {
padStr = " ";
}
String strData = Objects.requireNonNull(str).intern();
int strLen = strData.codePointCount(0, strData.length());
String padData = Objects.requireNonNull(padStr).intern();
int padLen = padData.codePointCount(0, padData.length());
if (padLen == 0) {
padStr = " ";
}
final int pads = size - strLen;
if (pads <= 0) {
return str;
}
String padding = "";
for (int i = 0; i < pads + 1; i++) {
padding += padStr;
}
return substr(padding, 0, pads).concat(str);
}
// Source: Jsonata4Java PadFunction
public static String rightPad(final String str, final int size, String padStr) {
if (str == null) {
return null;
}
if (padStr == null) {
padStr = " ";
}
String strData = Objects.requireNonNull(str).intern();
int strLen = strData.codePointCount(0, strData.length());
String padData = Objects.requireNonNull(padStr).intern();
int padLen = padData.codePointCount(0, padData.length());
if (padLen == 0) {
padStr = " ";
}
final int pads = size - strLen;
if (pads <= 0) {
return str;
}
String padding = "";
for (int i = 0; i < pads + 1; i++) {
padding += padStr;
}
return str.concat(substr(padding, 0, pads));
}
static class RegexpMatch {
String match;
int index;
List<String> groups;
@Override public String toString() {
return "regexpMatch "+match+" idx="+index+" groups="+groups;
}
}
/**
* Evaluate the matcher function against the str arg
*
* @param {*} matcher - matching function (native or lambda)
* @param {string} str - the string to match against
* @returns {object} - structure that represents the match(es)
*/
public static List<RegexpMatch> evaluateMatcher(Pattern matcher, String str) {
List<RegexpMatch> res = new ArrayList<>();
Matcher m = matcher.matcher(str);
while (m.find()) {
RegexpMatch rm = new RegexpMatch();
//System.out.println("grc="+m.groupCount()+" "+m.group(1));
rm.index = m.start();
rm.match = m.group();
List<String> groups = new ArrayList<>();
// Collect the groups
for (int g=1; g<=m.groupCount(); g++)
groups.add(m.group(g));
rm.groups = groups;
res.add(rm);
}
return res;
}
/**
* Tests if the str contains the token
* @param {String} str - string to test
* @param {String} token - substring or regex to find
* @returns {Boolean} - true if str contains token
*/
public static Boolean contains(String str, Object token) {
// undefined inputs always return undefined
if (str == null) {
return null;
}
boolean result;
if (token instanceof String) {
result = (str.indexOf((String)token) != -1);
} else if (token instanceof Pattern) {
var matches = evaluateMatcher((Pattern)token, str);
//if (dbg) System.out.println("match = "+matches);
//result = (typeof matches !== 'undefined');
//throw new Error("regexp not impl"); //result = false;
result = !matches.isEmpty();
} else {
throw new Error("unknown type to match: "+token);
}
return result;
}
/**
* Match a string with a regex returning an array of object containing details of each match
* @param {String} str - string
* @param {String} regex - the regex applied to the string
* @param {Integer} [limit] - max number of matches to return
* @returns {Array} The array of match objects
*/
public static List<Map> match(String str, Pattern regex, Integer limit) {
// undefined inputs always return undefined
if (str == null) {
return null;
}
// limit, if specified, must be a non-negative number
if (limit!=null && limit < 0) {
throw new JException("D3040", -1, limit
);
}
var result = Utils.createSequence();
var matches = evaluateMatcher(regex, str);
int max = Integer.MAX_VALUE;
if (limit!=null)
max = limit;
for (int i=0; i < matches.size(); i++) {
Map m = new LinkedHashMap<>();
RegexpMatch rm = matches.get(i);
// Convert to JSON map:
m.put("match", rm.match);
m.put("index", rm.index);
m.put("groups", rm.groups);
result.add(m);
if (i>=max)
break;
}
return (List)result;
}
/**
* Join an array of strings
* @param {Array} strs - array of string
* @param {String} [separator] - the token that splits the string
* @returns {String} The concatenated string
*/
public static String join(List<String> strs, String separator) {
// undefined inputs always return undefined
if (strs == null) {
return null;
}
// if separator is not specified, default to empty string
if (separator == null) {
separator = "";
}
return String.join(separator, strs);
}
static String safeReplacement(String in) {
// In JSONata and in Java the $ in the replacement test usually starts the insertion of a capturing group
// In order to replace a simple $ in Java you have to escape the $ with "\$"
// in JSONata you do this with a '$$'
// "\$" followed any character besides '<' and and digit into $ + this character
return in.replaceAll("\\$\\$", "\\\\\\$")
.replaceAll("([^\\\\]|^)\\$([^0-9^<])", "$1\\\\\\$$2")
.replaceAll("\\$$", "\\\\\\$"); // allow $ at end
}
/**
* Safe replaceAll
*
* In Java, non-existing groups cause an exception.
* Ignore these non-existing groups (replace with "")
*
* @param s
* @param pattern
* @param replacement
* @return
*/
static String safeReplaceAll(String s, Pattern pattern, Object _replacement) {
if (!(_replacement instanceof String))
return safeReplaceAllFn(s, pattern, _replacement);
String replacement = (String)_replacement;
replacement = safeReplacement(replacement);
Matcher m = pattern.matcher(s);
String r = null;
for (int i=0; i<10; i++) {
try {
r = m.replaceAll(replacement);
break;
} catch (IndexOutOfBoundsException e) {
String msg = e.getMessage();
// Message we understand needs to be:
// No group X
if (!msg.contains("No group")) throw e;
// Adjust replacement to remove the non-existing group
String g = "" + msg.charAt(msg.length()-1);
replacement = replacement.replace("$"+g, "");
}
}
return r;
}
/**
* Converts Java MatchResult to the Jsonata object format
* @param mr
* @return
*/
static Map toJsonataMatch(MatchResult mr) {
Map obj = new LinkedHashMap<>();
obj.put("match", mr.group());
List groups = new ArrayList<>();
for (int i=0; i<=mr.groupCount(); i++)
groups.add(mr.group(i));
obj.put("groups", groups);
return obj;
}
/**
* Regexp Replace with replacer function
* @param s
* @param pattern
* @param fn
* @return
*/
static String safeReplaceAllFn(String s, Pattern pattern, Object fn) {
Matcher m = pattern.matcher(s);
String r = null;
r = m.replaceAll(t -> { try {
Object res = funcApply(fn, List.of(toJsonataMatch(t)));
if (res instanceof String)
return (String)res;
else
return null;
} catch (Throwable e) {
e.printStackTrace();
}
return null;
});
return r;
}
/**
* Safe replaceFirst
*
* @param s
* @param pattern
* @param replacement
* @return
*/
static String safeReplaceFirst(String s, Pattern pattern, String replacement) {
replacement = safeReplacement(replacement);
Matcher m = pattern.matcher(s);
String r = null;
for (int i=0; i<10; i++) {
try {
r = m.replaceFirst(replacement);
break;
} catch (IndexOutOfBoundsException e) {
String msg = e.getMessage();
// Message we understand needs to be:
// No group X
if (!msg.contains("No group")) throw e;
// Adjust replacement to remove the non-existing group
String g = "" + msg.charAt(msg.length()-1);
replacement = replacement.replace("$"+g, "");
}
}
return r;
}
public static String replace(String str, Object pattern, Object replacement, Integer limit) {
if (str == null) {
return null;
}
if (pattern instanceof String)
if (((String)pattern).isEmpty())
throw new JException("Second argument of replace function cannot be an empty string", 0);
if (limit == null) {
if (pattern instanceof String) {
return str.replace((String)pattern, (String)replacement);
} else {
return safeReplaceAll(str, (Pattern)pattern, replacement);
}
} else {
if (limit<0)
throw new JException("Fourth argument of replace function must evaluate to a positive number", 0);
for (int i=0; i<limit; i++)
if (pattern instanceof String) {
str = str.replaceFirst((String)pattern, (String)replacement);
} else {
str = safeReplaceFirst(str, (Pattern)pattern, (String)replacement);
}
return str;
}
}
/**
* Base64 encode a string
* @param {String} str - string
* @returns {String} Base 64 encoding of the binary data
*/
public static String base64encode(String str) {
// undefined inputs always return undefined
if (str == null) {
return null;
}
try {
return Base64.getEncoder().encodeToString(str.getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/**
* Base64 decode a string
* @param {String} str - string
* @returns {String} Base 64 encoding of the binary data
*/
public static String base64decode(String str) {
// undefined inputs always return undefined
if (str == null) {
return null;
}
try {
return new String(Base64.getDecoder().decode(str), "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/**
* Encode a string into a component for a url
* @param {String} str - String to encode
* @returns {string} Encoded string
*/
public static String encodeUrlComponent(String str) {
// undefined inputs always return undefined
if (str == null) {
return null;
}
Utils.checkUrl(str);
return URLEncoder.encode(str, StandardCharsets.UTF_8)
.replaceAll("\\+", "%20")
.replaceAll("\\%21", "!")
.replaceAll("\\%27", "'")
.replaceAll("\\%28", "(")
.replaceAll("\\%29", ")")
.replaceAll("\\%7E", "~");
}
/**
* Encode a string into a url
* @param {String} str - String to encode
* @returns {string} Encoded string
*/
public static String encodeUrl(String str) {
// undefined inputs always return undefined
if (str == null) {
return null;
}
Utils.checkUrl(str);