forked from rayokota/jsonata-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.py
More file actions
2242 lines (1904 loc) · 74 KB
/
functions.py
File metadata and controls
2242 lines (1904 loc) · 74 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
#
# Copyright Robert Yokota
#
# 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.
#
# Derived from the following code:
#
# Project name: jsonata-java
# Copyright Dashjoin GmbH. https://dashjoin.com
# Licensed under the Apache License, Version 2.0 (the "License")
#
# Project name: elementpath
# Copyright (c), 2018-2021, SISSA (Scuola Internazionale Superiore di Studi Avanzati)
# This project is licensed under the MIT License, see LICENSE
import base64
import datetime
import decimal
import functools
import inspect
import json
import math
import random
import re
import sys
import unicodedata
import urllib.parse
from dataclasses import dataclass
from typing import Any, AnyStr, Mapping, NoReturn, Optional, Sequence, Callable, Type, Union
from jsonata import datetimeutils, jexception, parser, utils
class Functions:
#
# Sum function
# @param {Object} args - Arguments
# @returns {number} Total value of arguments
#
@staticmethod
def sum(args: Optional[Sequence[float]]) -> Optional[float]:
# undefined inputs always return undefined
if args is None:
return None
return sum(args)
#
# Count function
# @param {Object} args - Arguments
# @returns {number} Number of elements in the array
#
@staticmethod
def count(args: Optional[Sequence[Any]]) -> float:
# undefined inputs always return undefined
if args is None:
return 0
return len(args)
#
# Max function
# @param {Object} args - Arguments
# @returns {number} Max element in the array
#
@staticmethod
def max(args: Optional[Sequence[float]]) -> Optional[float]:
# undefined inputs always return undefined
if args is None or not args:
return None
return max(args)
#
# Min function
# @param {Object} args - Arguments
# @returns {number} Min element in the array
#
@staticmethod
def min(args: Optional[Sequence[float]]) -> Optional[float]:
# undefined inputs always return undefined
if args is None or not args:
return None
return min(args)
#
# Average function
# @param {Object} args - Arguments
# @returns {number} Average element in the array
#
@staticmethod
def average(args: Optional[Sequence[float]]) -> Optional[float]:
# undefined inputs always return undefined
if args is None or not args:
return None
return sum(args) / len(args)
#
# Stringify arguments
# @param {Object} arg - Arguments
# @param {boolean} [prettify] - Pretty print the result
# @returns {String} String from arguments
#
@staticmethod
def string(arg: Optional[Any], prettify: Optional[bool]) -> Optional[str]:
if isinstance(arg, utils.Utils.JList):
if arg.outer_wrapper:
arg = arg[0]
if arg is None:
return None
# see https://docs.jsonata.org/string-functions#string: Strings are unchanged
if isinstance(arg, str):
return str(arg)
return Functions._string(arg, bool(prettify))
@staticmethod
def _string(arg: Any, prettify: bool) -> str:
from jsonata import jsonata
if isinstance(arg, (jsonata.Jsonata.JFunction, parser.Parser.Symbol)):
return ""
if prettify:
return json.dumps(arg, cls=Functions.Encoder, indent=" ")
else:
return json.dumps(arg, cls=Functions.Encoder, separators=(',', ':'))
class Encoder(json.JSONEncoder):
def encode(self, arg):
if not isinstance(arg, bool) and isinstance(arg, (int, float)):
d = decimal.Decimal(arg)
res = Functions.remove_exponent(d, decimal.Context(prec=15))
return str(res).lower()
return super().encode(arg)
def default(self, arg):
from jsonata import jsonata
if arg is utils.Utils.NULL_VALUE:
return None
if isinstance(arg, (jsonata.Jsonata.JFunction, parser.Parser.Symbol)):
return ""
return super().default(arg)
@staticmethod
def remove_exponent(d: decimal.Decimal, ctx: decimal.Context) -> decimal.Decimal:
# Adapted from https://docs.python.org/3/library/decimal.html#decimal-faq
if d == d.to_integral():
try:
return d.quantize(decimal.Decimal(1), context=ctx)
except decimal.InvalidOperation:
pass
return d.normalize(ctx)
#
# Validate input data types.
# This will make sure that all input data can be processed.
#
# @param arg
# @return
#
@staticmethod
def validate_input(arg: Optional[Any]) -> None:
from jsonata import jsonata
if arg is None or arg is utils.Utils.NULL_VALUE:
return
if isinstance(arg, (jsonata.Jsonata.JFunction, parser.Parser.Symbol)):
return
if isinstance(arg, bool):
return
if isinstance(arg, (int, float)):
return
if isinstance(arg, str):
return
if isinstance(arg, dict):
for k, v in arg.items():
Functions.validate_input(k)
Functions.validate_input(v)
return
if isinstance(arg, list):
for v in arg:
Functions.validate_input(v)
return
# Throw error for unknown types
raise ValueError(
"Only JSON types (values, Map, List) are allowed as input. Unsupported type: " + str(type(arg)))
#
# 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
#
@staticmethod
def substring(string: Optional[str], start: Optional[float], length: Optional[float]) -> Optional[str]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
start = int(start) if start is not None else None
length = int(length) if length is not None else None
# not used: var strArray = stringToArray(string)
str_length = len(string)
if str_length + start < 0:
start = 0
if length is not None:
if length <= 0:
return ""
return Functions.substr(string, start, length)
return Functions.substr(string, start, str_length)
#
# 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.
#
@staticmethod
def substr(string: str, start: int, length: int) -> str:
# below has to convert start and length for emojis and unicode
orig_len = len(string)
str_data = string
str_len = len(str_data)
if start >= str_len:
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 = start if start >= 0 else (0 if (str_len + start) < 0 else str_len + 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 is None:
length = len(str_data)
elif length < 0:
# If length is 0 or negative, substr() returns an empty string.
return ""
elif length > len(str_data):
length = len(str_data)
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 >= orig_len:
return ""
# collect length characters (unless it reaches the end of the string
# first, in which case it will return fewer)
end = start + length
if end > orig_len:
end = orig_len
return str_data[start:end]
#
# Create substring up until a character
# @param {String} str - String to evaluate
# @param {String} chars - Character to define substring boundary
# @returns {*} Substring
#
@staticmethod
def substring_before(string: Optional[str], chars: Optional[str]) -> Optional[str]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
if chars is None:
return string
pos = string.find(chars)
if pos > -1:
return string[0:pos]
else:
return string
#
# Create substring after a character
# @param {String} str - String to evaluate
# @param {String} chars - Character to define substring boundary
# @returns {*} Substring
#
@staticmethod
def substring_after(string: Optional[str], chars: Optional[str]) -> Optional[str]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
pos = string.find(chars)
if pos > -1:
return string[pos + len(chars):]
else:
return string
#
# Lowercase a string
# @param {String} str - String to evaluate
# @returns {string} Lowercase string
#
@staticmethod
def lowercase(string: Optional[str]) -> Optional[str]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
return string.casefold()
#
# Uppercase a string
# @param {String} str - String to evaluate
# @returns {string} Uppercase string
#
@staticmethod
def uppercase(string: Optional[str]) -> Optional[str]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
return string.upper()
#
# length of a string
# @param {String} str - string
# @returns {Number} The number of characters in the string
#
@staticmethod
def length(string: Optional[str]) -> Optional[int]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
return len(string)
#
# Normalize and trim whitespace within a string
# @param {string} str - string to be trimmed
# @returns {string} - trimmed string
#
@staticmethod
def trim(string: Optional[str]) -> Optional[str]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
if not string:
return ""
# normalize whitespace
result = re.sub("[ \t\n\r]+", " ", string)
if result[0] == ' ':
# strip leading space
result = result[1:]
if result == "":
return ""
if result[len(result) - 1] == ' ':
# strip trailing space
result = result[0:len(result) - 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
#
@staticmethod
def pad(string: Optional[str], width: Optional[int], char: Optional[str]) -> Optional[str]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
if char is None or not char:
char = " "
# match JS: truncate width to integer
if width is not None:
try:
width = int(width)
except Exception:
width = 0
if width < 0:
result = Functions.left_pad(string, -width, char)
else:
result = Functions.right_pad(string, width, char)
return result
# Source: Jsonata4Java PadFunction
@staticmethod
def left_pad(string: Optional[str], size: Optional[int], pad_str: Optional[str]) -> Optional[str]:
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
if pad_str is None:
pad_str = " "
str_data = string
str_len = len(str_data)
if not pad_str:
pad_str = " "
pads = size - str_len
if pads <= 0:
return string
padding = ""
i = 0
while i < pads + 1:
padding += pad_str
i += 1
return Functions.substr(padding, 0, pads) + string
# Source: Jsonata4Java PadFunction
@staticmethod
def right_pad(string: Optional[str], size: Optional[int], pad_str: Optional[str]) -> Optional[str]:
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
if pad_str is None:
pad_str = " "
str_data = string
str_len = len(str_data)
if not pad_str:
pad_str = " "
pads = size - str_len
if pads <= 0:
return string
padding = ""
i = 0
while i < pads + 1:
padding += pad_str
i += 1
return string + Functions.substr(padding, 0, pads)
@dataclass
class RegexpMatch:
match: str
index: int
groups: Sequence[AnyStr]
#
# 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)
#
@staticmethod
def evaluate_matcher(matcher: re.Pattern, string: Optional[str]) -> list[RegexpMatch]:
res = []
matches = matcher.finditer(string)
for m in matches:
groups = []
# Collect the groups
g = 1
while g <= len(m.groups()):
groups.append(m.group(g))
g += 1
rm = Functions.RegexpMatch(m.group(), m.start(), groups)
rm.groups = groups
res.append(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
#
@staticmethod
def contains(string: Optional[str], token: Union[None, str, re.Pattern]) -> Optional[bool]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
return None
result = False
if isinstance(token, str):
result = (string.find(str(token)) != - 1)
elif isinstance(token, re.Pattern):
matches = Functions.evaluate_matcher(token, string)
# if (dbg) System.out.println("match = "+matches)
# result = (typeof matches !== 'undefined')
# throw new Error("regexp not impl"); //result = false
result = bool(matches)
else:
raise RuntimeError("unknown type to match: " + str(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
#
@staticmethod
def match_(string: Optional[str], regex: Optional[re.Pattern], limit: Optional[int]) -> Optional[list[dict[str, Any]]]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
# limit, if specified, must be a non-negative number
if limit is not None and limit < 0:
raise jexception.JException("D3040", -1, limit)
result = utils.Utils.create_sequence()
matches = Functions.evaluate_matcher(regex, string)
max = sys.maxsize
if limit is not None:
max = limit
for i, rm in enumerate(matches):
m = {"match": rm.match, "index": rm.index, "groups": rm.groups}
# Convert to JSON map:
result.append(m)
if i >= max:
break
return 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
#
@staticmethod
def join(strs: Optional[Sequence[str]], separator: Optional[str]) -> Optional[str]:
# undefined inputs always return undefined
if strs is None:
return None
# if separator is not specified, default to empty string
if separator is None:
separator = ""
return separator.join(strs)
@staticmethod
def safe_replacement(in_: str) -> str:
result = in_
# Replace "$<num>" with "\<num>" for Python regex
result = re.sub(r"\$(\d+)", r"\\g<\g<1>>", result)
# Replace "$$" with "$"
result = re.sub("\\$\\$", "$", result)
return result
#
# Safe replaceAll
#
# In Java, non-existing groups cause an exception.
# Ignore these non-existing groups (replace with "")
#
# @param s
# @param pattern
# @param replacement
# @return
#
@staticmethod
def safe_replace_all(s: str, pattern: re.Pattern, replacement: Optional[Any]) -> Optional[str]:
if not (isinstance(replacement, str)):
return Functions.safe_replace_all_fn(s, pattern, replacement)
replacement = str(replacement)
replacement = Functions.safe_replacement(replacement)
r = None
for i in range(0, 10):
try:
r = re.sub(pattern, replacement, s)
break
except Exception as e:
msg = str(e)
# Message we understand needs to be:
# invalid group reference <g> at position <p>
m = re.match(r"invalid group reference (\d+) at position (\d+)", msg)
if m is None:
raise e
g = m.group(1)
suffix = g[-1]
prefix = g[:-1]
# Try capturing a smaller numbered group, e.g. "\g<1>2" instead of "\g<12>"
replace = "" if not prefix else r"\g<" + prefix + ">" + suffix
# Adjust replacement to remove the non-existing group
replacement = replacement.replace(r"\g<" + g + ">", replace)
return r
#
# Converts Java MatchResult to the Jsonata object format
# @param mr
# @return
#
@staticmethod
def to_jsonata_match(mr: re.Match[str]) -> dict[str, list[str]]:
obj = {"match": mr.group()}
groups = []
i = 0
while i <= len(mr.groups()):
groups.append(mr.group(i))
i += 1
obj["groups"] = groups
return obj
#
# Regexp Replace with replacer function
# @param s
# @param pattern
# @param fn
# @return
#
@staticmethod
def safe_replace_all_fn(s: str, pattern: re.Pattern, fn: Optional[Any]) -> str:
def replace_fn(t):
res = Functions.func_apply(fn, [Functions.to_jsonata_match(t)])
if isinstance(res, str):
return res
else:
raise jexception.JException("D3012", -1)
r = re.sub(pattern, replace_fn, s)
return r
#
# Safe replaceFirst
#
# @param s
# @param pattern
# @param replacement
# @return
#
@staticmethod
def safe_replace_first(s: str, pattern: re.Pattern, replacement: str) -> Optional[str]:
replacement = Functions.safe_replacement(replacement)
r = None
for i in range(0, 10):
try:
r = re.sub(pattern, replacement, s, count=1)
break
except Exception as e:
msg = str(e)
# Message we understand needs to be:
# invalid group reference <g> at position <p>
m = re.match(r"invalid group reference (\d+) at position (\d+)", msg)
if m is None:
raise e
g = m.group(1)
suffix = g[-1]
prefix = g[:-1]
# Try capturing a smaller numbered group, e.g. "\g<1>2" instead of "\g<12>"
replace = "" if not prefix else r"\g<" + prefix + ">" + suffix
# Adjust replacement to remove the non-existing group
replacement = replacement.replace(r"\g<" + g + ">", replace)
return r
@staticmethod
def replace(string: Optional[str], pattern: Union[str, re.Pattern], replacement: Optional[Any], limit: Optional[int]) -> Optional[str]:
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
if isinstance(pattern, str):
if not pattern:
raise jexception.JException("Second argument of replace function cannot be an empty string", 0)
if limit is not None and limit < 0:
raise jexception.JException("Fourth argument of replace function must evaluate to a positive number", 0)
def string_replacer(match):
result = ''
position = 0
repl = str(replacement)
while position < len(repl):
index = repl.find('$', position)
if index == -1:
result += repl[position:]
break
result += repl[position:index]
position = index + 1
if position < len(repl):
dollar_val = repl[position]
if dollar_val == '$':
result += '$'
position += 1
elif dollar_val == '0':
result += match.group(0)
position += 1
else:
max_digits = len(str(len(match.groups())))
group_num = repl[position:position+max_digits]
if group_num.isdigit():
group_index = int(group_num)
if 0 < group_index <= len(match.groups()):
result += match.group(group_index) or ''
position += len(group_num)
else:
result += '$'
else:
result += '$'
else:
result += '$'
return result
if callable(replacement):
replacer = lambda m: replacement(m.groupdict())
elif isinstance(replacement, str):
replacer = string_replacer
else:
replacer = lambda m: str(replacement)
if isinstance(pattern, str):
# Use string methods for literal string patterns
result = ''
position = 0
count = 0
while True:
if limit is not None and count >= limit:
result += string[position:]
break
index = string.find(pattern, position)
if index == -1:
result += string[position:]
break
result += string[position:index]
match = re.match(re.escape(pattern), string[index:])
result += replacer(match)
position = index + len(pattern)
count += 1
return result
else:
# Use regex for pattern objects
if limit is None:
return Functions.safe_replace_all(string, pattern, replacement)
else:
count = 0
result = string
while count < limit:
result = Functions.safe_replace_first(result, pattern, str(replacement))
count += 1
return result
#
# Base64 encode a string
# @param {String} str - string
# @returns {String} Base 64 encoding of the binary data
#
@staticmethod
def base64encode(string: Optional[str]) -> Optional[str]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
try:
return base64.b64encode(string.encode("utf-8")).decode("utf-8")
except Exception as e:
return None
#
# Base64 decode a string
# @param {String} str - string
# @returns {String} Base 64 encoding of the binary data
#
@staticmethod
def base64decode(string: Optional[str]) -> Optional[str]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
try:
return base64.b64decode(string.encode("utf-8")).decode("utf-8")
except Exception as e:
return None
#
# Encode a string into a component for a url
# @param {String} str - String to encode
# @returns {string} Encoded string
#
@staticmethod
def encode_url_component(string: Optional[str]) -> Optional[str]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
# See https://stackoverflow.com/questions/946170/equivalent-javascript-functions-for-pythons-urllib-parse-quote-and-urllib-par
return urllib.parse.quote(string, safe="~()*!.'")
#
# Encode a string into a url
# @param {String} str - String to encode
# @returns {string} Encoded string
#
@staticmethod
def encode_url(string: Optional[str]) -> Optional[str]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
# See https://stackoverflow.com/questions/946170/equivalent-javascript-functions-for-pythons-urllib-parse-quote-and-urllib-par
return urllib.parse.quote(string, safe="~@#$&()*!+=:;,.?/'")
#
# Decode a string from a component for a url
# @param {String} str - String to decode
# @returns {string} Decoded string
#
@staticmethod
def decode_url_component(string: Optional[str]) -> Optional[str]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
# See https://stackoverflow.com/questions/946170/equivalent-javascript-functions-for-pythons-urllib-parse-quote-and-urllib-par
return urllib.parse.unquote(string, errors="strict")
#
# Decode a string from a url
# @param {String} str - String to decode
# @returns {string} Decoded string
#
@staticmethod
def decode_url(string: Optional[str]) -> Optional[str]:
# undefined inputs always return undefined
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
# See https://stackoverflow.com/questions/946170/equivalent-javascript-functions-for-pythons-urllib-parse-quote-and-urllib-par
return urllib.parse.unquote(string, errors="strict")
@staticmethod
def split(string: Optional[str], pattern: Union[str, Optional[re.Pattern]], limit: Optional[float]) -> Optional[list[str]]:
if string is None:
return None
if string is utils.Utils.NULL_VALUE:
raise jexception.JException("T0410", -1)
if limit is not None and int(limit) < 0:
raise jexception.JException("D3020", -1, string)
result = []
if limit is not None and int(limit) == 0:
return result
if isinstance(pattern, str):
sep = str(pattern)
if not sep:
# $split("str", ""): Split string into characters
lim = int(limit) if limit is not None else sys.maxsize
i = 0
while i < len(string) and i < lim:
result.append(string[i])
i += 1
else:
# Quote separator string + preserve trailing empty strings (-1)
result = string.split(sep, -1)
else:
result = pattern.split(string)
if limit is not None and int(limit) < len(result):
result = result[0:int(limit)]
return result
EXPONENT_PIC = re.compile(r'\d[eE]\d')
#
# Formats a number into a decimal string representation using XPath 3.1 F&O fn:format-number spec
# @param {number} value - number to format
# @param {String} picture - picture string definition
# @param {Object} [options] - override locale defaults
# @returns {String} The formatted string
#
# Adapted from https://github.com/sissaschool/elementpath
@staticmethod
def format_number(value: Optional[float], picture: Optional[str], decimal_format: Optional[Mapping[str, str]]) -> Optional[str]:
if decimal_format is None:
decimal_format = {}
pattern_separator = decimal_format.get('pattern-separator', ';')
sub_pictures = picture.split(pattern_separator)
if len(sub_pictures) > 2:
raise jexception.JException('D3080', -1)
decimal_separator = decimal_format.get('decimal-separator', '.')