-
Notifications
You must be signed in to change notification settings - Fork 0
/
VariableMan.groovy
1942 lines (1736 loc) · 79.8 KB
/
VariableMan.groovy
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
package jaemisseo.man
import jaemisseo.man.util.SimpleDataUtil
import jaemisseo.man.util.SimpleSplitUtil
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.security.CodeSource
import java.text.SimpleDateFormat
import java.util.regex.Matcher
import java.util.regex.Pattern
/**
* Created with IntelliJ IDEA.
* User: sujkim
* Date: 9/30/16
* Time: 4:25 PM
* To change this template use File | Settings | File Templates.
*/
class VariableMan {
static final Logger logger = LoggerFactory.getLogger(this.getClass());
/*************************
* CONSTRUCTORS
*************************/
VariableMan(){
init()
}
VariableMan(Map<String, Object> variableStringMapToPut){
putVariables(variableStringMapToPut)
init()
}
VariableMan(Map<String, Object> variableStringMapToPut, Map<String, Closure> funcMapToPut){
putVariables(variableStringMapToPut)
putFuncs(funcMapToPut)
init()
}
VariableMan(String charset){
this.charset = charset
init()
}
VariableMan(String charset, Map<String, Object> variableStringMapToPut){
this.charset = charset
putVariables(variableStringMapToPut)
init()
}
void init(){
logger.trace("......................... [INIT] VariableMan")
putVariables(getBasicVariableMap())
putVariableClosures(getBasicVariableClosureMap())
putFuncs(getBasicFuncMap())
putConditionFuncs(getBasicConditionFuncMap())
putStreamFuncs(getBasicStreamFuncMap())
putConditionComputerFuncs(getBasicConditionComputerFuncMap())
}
/**
* Error Message
*/
static final String VAR1 = "Doesn't Exist Code Rule."
static final String VAR2 = "Code Number Exceeds Limit."
static final String VAR3 = "It Needs Number Type Value To Set Length."
static final String VAR4 = "It is Unknown Code Rule's Function."
static final String VAR5 = "It Has Bad Syntax."
static final String VAR6 = "It Has Bad Syntax - brace does not match."
static final String VAR7 = "It Has Bad Syntax - bracket does not match."
static final String VAR8 = "It Has Bad Syntax - nothing beetween braces."
// enum ErrorMessage{
// VAR1(1, "Doesn't Exist Code Rule."),
// VAR2(2, "Code Number Exceeds Limit."),
// VAR3(3, "It Needs Number Type Value To Set Length."),
// VAR4(4, "It is Unknown Code Rule's Function."),
// VAR5(5, "It Has Bad Syntax."),
// VAR6(6, "It Has Bad Syntax - brace does not match."),
// VAR7(7, "It Has Bad Syntax - bracket does not match."),
// VAR8(8, "It Has Bad Syntax - nothing beetween braces.")
//
// ErrorMessage(int code, String msg){ this.code = code; this.msg = msg }
// final int code
// final String msg
// String prefix = "VAR-"
// String getMsg(){ return "${prefix}${code}: ${msg}" }
// }
/**
* ConditionNotMatchedFinishException
*/
class ConditionNotMatchedFinishException extends Exception{
}
/**
* You Can Create Function's Properties With This Object
*/
class OnePartObject {
String partValue = ''
String partContent = ''
String originalCode = ''
String valueCode = ''
String substitutes = ''
Object originalValue = null
String parsedValue = ''
byte[] bytes
int startIndex = 0
int endIndex = 0
int length = 0
int userSetLength = 0
int byteLength = 0
int charLength = 0
boolean isCode = false
boolean isExistCode = false
boolean isOver = false
//Condition Method - Stream
boolean modeStream = false
List<String> reducedCollection = null
StringBuilder virtualRuleBuilderInStream = null;
Integer okStreamLevel = 0
Integer nowStreamLevel = 0
boolean checkStream(){
return this.okStreamLevel == this.nowStreamLevel
}
//Condition Method - If
boolean modeIf = false
Integer okIfSeq = 0
Integer nowIfSeq = 0
//Check Condition
boolean checkConditionNowSeq(){
return this.okIfSeq == this.nowIfSeq
}
String overValue = ''
String funcNm = ''
String[] members = []
Map<String, String[]> funcNameMemberListMap = [:]
boolean hasFunc(String functionName){
return funcNameMemberListMap.containsKey(functionName.toUpperCase())
}
String[] getMember(String functionName){
return funcNameMemberListMap[functionName.toUpperCase()]
}
String getMember(String functionName, int memberIndex){
String[] members = getMember(functionName)
return members ? members[memberIndex] : null
}
}
Map<String, Object> variableStringMap = [:]
Map<String, Closure> variableClosureMap = [:]
Map<String, Closure> funcMap = [:]
Map<String, Closure> conditionFuncMap = [:]
Map<String, Closure> streamFuncMap = [:]
Map<String, Closure> conditionComputerFuncMap = [:]
boolean modeDebug = false
boolean modeMustExistCodeRule = true
boolean modeExistCodeOnly = false
boolean modeExistFunctionOnly = true
String charset
/* Pattern - Variable */
private String variableSign = '$'
private String patternBodyToGetVariable = '[{][^{}]*\\w+[^{}]*[}]'
private String patternBodyStartToGetVariable = '[{][^{}]*'
private String patternBodyContentsToGetVariable = '\\w+'
private String patternBodyEndToGetVariable = '[^{}]*[}]'
private String patternToGetVariable = "[" +variableSign+ "]" + patternBodyStartToGetVariable + patternBodyContentsToGetVariable + patternBodyEndToGetVariable // If variable contains some word in ${} then convert to User Set Value or...
/* Pattern - Member */
private String patternToSeperateMemebers = ',(?=(?:[^"]*"[^"]*")*[^"]*$)(?=(?:[^\']*\'[^\']*\')*[^\']*$)'
private String patternToGetMembers = '[(][^(]*[^)]*[)]' //TODO: addVariable()에 들어가는 파라미터르 인식하기 위해서는 매치패턴의 업데이트 필요
static private String charDoubleQuote = '"'
static private String charSingleQuote = "'"
/* Pattern - Func */
private String patternToSeperateFuncs = '\\s*[.](?![^(]*[)])\\s*'
/**
* You Can Set Debug Mode To Watch Detail
* @param modeDebug
* @return
*/
VariableMan setModeDebug(boolean modeDebug){
this.modeDebug = modeDebug
return this
}
VariableMan setModeMustExistCodeRule(boolean modeMustExistCodeRule){
this.modeMustExistCodeRule = modeMustExistCodeRule
return this
}
VariableMan setModeExistCodeOnly(boolean modeExistCodeOnly){
this.modeExistCodeOnly = modeExistCodeOnly
return this
}
VariableMan setModeExistFunctionOnly(boolean modeExistFunctionOnly){
this.modeExistFunctionOnly = modeExistFunctionOnly
return this
}
VariableMan setVariableSign(String variableSign){
this.variableSign = variableSign
if (variableSign){
this.patternToGetVariable = "[" +variableSign+ "]" + patternBodyStartToGetVariable + patternBodyContentsToGetVariable + patternBodyEndToGetVariable
}else{
this.patternToGetVariable = patternBodyStartToGetVariable + patternBodyContentsToGetVariable + patternBodyEndToGetVariable
}
return this
}
/**
* You Can Put Variable
* [ VariableName(String) : VariableValue(String) ]
* Please Do Not Set These Names => 'date', 'random'
* @param variableStringMapToAdd
* @return
*/
VariableMan putVariables(Map<String, Object> variableStringMapToPut){
if (variableStringMapToPut){
//- Apply to Variable-Map
variableStringMapToPut = convertToPropertiesMap(variableStringMapToPut)
if (logger.isTraceEnabled()){
variableStringMapToPut.each{
logger.trace("[${it.key}] ${it.value}")
}
}
//Put
this.variableStringMap.putAll(variableStringMapToPut)
}
return this
}
static Map<String, Object> convertToPropertiesMap(Map<String, Object> variableStringMap){
boolean subObjectExists = variableStringMap.values().any{ it instanceof Map || it instanceof List }
if (subObjectExists){
logger.trace('Add Variable (from MultiDepth Map)')
variableStringMap = toPropertiesMap(variableStringMap)
}else{
logger.trace('Add Variable (from SingleDepth Map)')
}
return variableStringMap
}
static Map<String, Object> toPropertiesMap(Map parameters){
Map<String, Object> concatKeyStringValueMap = [:]
return toPropertiesMap(parameters, '', concatKeyStringValueMap)
}
static Map<String, Object> toPropertiesMap(Map parameters, String prevKey, Map<String, Object> concatKeyStringValueMap){
parameters.keySet().each{ String key ->
String concatKey = (prevKey) ? prevKey + '.' + key : key
def value = parameters[key]
if (value instanceof Map)
toPropertiesMap(value, concatKey, concatKeyStringValueMap)
else{
concatKeyStringValueMap[concatKey] = value
}
}
return concatKeyStringValueMap
}
/**
* You Can Delete Variable
* [ VariableName(String), VariableName(String) ]
* Please Do Not Set These Names => 'date', 'random'
* @param variableStringMapToAdd
* @return
*/
VariableMan delVariables(List<String> variableStringList){
if (variableStringList){
variableStringList.each{
this.variableStringMap.remove(it)
}
}
return this
}
/**
* You Can Put Variable
* [ VariableName(String) : Variable Function(Closure) ]
* Please Refer To getBasicVariableClosureMap()
* @param variableFuncMapToPut
* @return
*/
VariableMan putVariableClosures(Map<String, Closure> variableFuncMapToPut){
if (variableFuncMapToPut)
this.variableClosureMap.putAll(variableFuncMapToPut)
return this
}
/**
* You Can Create Custom Function
* [ FunctionName(String) : Function(Closure) ]
* Please Refer To getBasicFuncMap()
* @param funcMapToPut
*/
VariableMan putFuncs(Map<String, Closure> funcMapToPut){
this.funcMap.putAll(funcMapToPut)
return this
}
VariableMan putConditionFuncs(Map<String, Closure> funcMapToPut){
this.conditionFuncMap.putAll(funcMapToPut)
return this
}
VariableMan putStreamFuncs(Map<String, Closure> funcMapToPut){
this.streamFuncMap.putAll(funcMapToPut)
return this
}
VariableMan putConditionComputerFuncs(Map<Object, Closure> funcMapToPut){
funcMapToPut.each{ key, value ->
if (key instanceof String){
this.conditionComputerFuncMap.put(key, value)
}else if(key instanceof List<String>){
key.each{k ->
this.conditionComputerFuncMap.put(k, value)
}
}
}
return this
}
/**
* You Can Set CharacterSet
* ex1) 'euc-kr'
* ex2) 'utf-8'
* @param charset
* @return
*/
VariableMan setCharset(String charset){
this.charset = charset
return this
}
/**
* Parse !!!
* @param codeRule
* @return
* @throws java.lang.Exception
*/
Object parse(Object codeRule){
parse(codeRule, this.variableStringMap)
}
String parseString(String codeRule) {
return parseString(codeRule, this.variableStringMap)
}
Object parseObject(Object codeRule) {
return parseObject(codeRule, this.variableStringMap)
}
private String parseVirtualRuleContent(String codeRuleContent, Object itItem, Map<String, Object> vsMap, Map<String, Closure> vcMap){
OnePartObject partObj = new VariableMan(vsMap, vcMap)
.setModeMustExistCodeRule(this.modeMustExistCodeRule)
.setModeExistCodeOnly(this.modeExistCodeOnly)
.setModeExistFunctionOnly(this.modeExistFunctionOnly)
.setCharset(this.getCharset())
.setVariableSign(this.variableSign)
.setModeExistCodeOnly(false)
.putVariables([it:itItem])
.parseCodeContent(codeRuleContent)
makePartResult(partObj)
return partObj.parsedValue
}
/**
* Parse !!!
* @param codeRule
* @param variableStringMap
* @return
* @throws java.lang.Exception
*/
Object parse(Object codeRule, Map<String, Object> variableStringMap) {
switch(codeRule){
case {codeRule instanceof String}:
return parseString(codeRule, variableStringMap)
break
default:
return parseObject(codeRule, variableStringMap)
break
}
}
String parseString(String codeRule, Map<String, Object> variableStringMap) {
logger.trace("......................... Start parse string: ${codeRule}")
//- Apply to Variable-Map
variableStringMap = convertToPropertiesMap(variableStringMap)
//- Validation
validateCodeRule(codeRule)
//- Parse data
List<OnePartObject> partObjectList = parsedDataList(codeRule, variableStringMap)
logger.trace("..... Creating String Data from Parsed Data")
int allCharLength = 0
int allByteLength = 0
int allUserSetLength = 0
List parsedPartStringList = partObjectList.collect { OnePartObject partObj ->
// CASE - DEBUG MODE
if (modeDebug && partObj.substitutes){
allUserSetLength += partObj.userSetLength
allByteLength += partObj.byteLength
allCharLength += partObj.charLength
logger.debug "////////// ${partObj.partValue}"
logger.debug "[${partObj.substitutes}]"
logger.debug "Length: ${partObj.charLength} / Byte: ${partObj.byteLength} / Your Set: ${partObj.userSetLength}"
if (partObj.userSetLength !=0 && partObj.userSetLength != partObj.byteLength){
logger.debug "!!! !!! !!! !!! !!!"
logger.debug "!!! Not Matched !!!"
logger.debug "!!! !!! !!! !!! !!!"
}
}
return partObj.parsedValue
}
logger.trace('......................... Finish parse string')
if (modeDebug){
println ""
println "//////////////////////////////////////////////////"
println "////// ALL LENGTH ////////////////////////////////"
println "//////////////////////////////////////////////////"
println "SETUP LENGTH : ${allUserSetLength}"
println " BYTE LENGTH : ${allByteLength}"
println " CHAR LENGTH : ${allCharLength}"
println ""
}
return parsedPartStringList.join('')
}
Object parseObject(Object codeRule, Map<String, Object> variableStringMap) {
switch (codeRule){
case {codeRule instanceof Map}:
codeRule.each{ key, item ->
if (item instanceof String)
codeRule[key] = parseString(item, variableStringMap)
else
parseObject(item, variableStringMap)
}
break
case {codeRule instanceof List}:
codeRule.eachWithIndex{ item, i ->
if (item instanceof String)
codeRule[i] = parseString(item, variableStringMap)
else
parseObject(item, variableStringMap)
}
break
case {codeRule instanceof String}:
return parseString(codeRule, variableStringMap)
break
}
}
Map<String, String> matchVariableMap(String codeRule, String targetString) {
Map<String, String> variableStringMap = [:];
//- Validation
validateCodeRule(codeRule, true)
//- Get String In ${ } step by step
List<OnePartObject> partObjects = parsedDataList(codeRule)
String regex = codeRuleToPattern(partObjects)
Pattern pattern = Pattern.compile(regex)
Matcher matcher = pattern.matcher( targetString )
//- Put captured values
boolean matched = matcher.matches()
Integer groupCount = matcher.groupCount()
boolean thisIsCapturePattern = matched && groupCount > 0
if (thisIsCapturePattern){
partObjects.each{
if (it.isCode){
String capturedValue = matcher.group(it.valueCode)
variableStringMap.put(it.valueCode, capturedValue)
}
}
}
return variableStringMap
}
//- Variable(${}) to REGEX(.*)
String codeRuleToPattern(List<OnePartObject> partObjectList){
StringBuilder sb = new StringBuilder();
partObjectList.eachWithIndex{ part, i ->
if (part.isCode){
sb.append("(?<").append(part.valueCode).append(">.*)")
}else{
String convertedString = toRegexExpression(part.partValue);
// String convertedString = part.partValue;
sb.append(convertedString);
}
}.join("")
String regex = sb.toString()
return regex
}
static String toRegexExpression(String string){
String regexpStr = toSlash(string)
.replace('(', '\\(').replace(')', '\\)')
.replace('[', '\\[').replace(']', '\\]')
.replace('.', '\\.').replace('$', '\\$')
.replace('*',"[^\\/\\\\]*")
.replace('[^\\/\\\\]*[^\\/\\\\]*/','(\\S*[\\/\\\\]|)')
.replace('[^\\/\\\\]*[^\\/\\\\]*',"\\S*")
// return regexpStr.replace("\\", "\\\\")
return regexpStr
}
static toSlash(String path){
return path?.replaceAll(/[\/\\]+/, '/')
}
List<OnePartObject> parsedDataList(String codeRule){
return parsedDataList(codeRule, this.variableStringMap)
}
List<OnePartObject> parsedDataList(String codeRule, Map<String, Object> variableStringMap) {
//- Validation
validateCodeRule(codeRule)
//- Parse data
return parsedDataList(codeRule, variableStringMap, this.variableClosureMap, this.patternToGetVariable)
}
List<OnePartObject> parsedDataList(String codeRule, Map<String, Object> variableStringMap, Map<String, Closure> variableClosureMap, String patternToGetVariable){
logger.trace("..... Analysis code rule")
//- Get String In ${ } step by step
Matcher matchedList = Pattern.compile(patternToGetVariable).matcher(codeRule)
List<String> splitWithCodeRuleList = codeRule?.split(patternToGetVariable)?.toList()
List<String> codeList = matchedList ? matchedList?.collect{ it } : []
logger.trace("..... Creating Part-Object from parsed datas with code rule: (variable: ${codeList.size()})")
List<OnePartObject> partObjectList = []
int cnt = -1
codeList.each{ String code ->
cnt++
if (splitWithCodeRuleList && splitWithCodeRuleList[cnt]){
partObjectList << generateOnePartObjectForString(splitWithCodeRuleList[cnt])
}
try{
partObjectList << generateOnePartObjectForVariable(code, variableStringMap, variableClosureMap)
}catch(ConditionNotMatchedFinishException cnmfe){
//Exit
}
}
cnt++
if (splitWithCodeRuleList && splitWithCodeRuleList[cnt]){
partObjectList << generateOnePartObjectForString(splitWithCodeRuleList[cnt])
}
logger.trace("..... Remaking Part-Object")
int index = 0
partObjectList.each{ OnePartObject partObj ->
makePartResult(partObj)
partObj.startIndex = index
partObj.endIndex = index + partObj.charLength + (partObj.charLength == 0 ? 0 : -1)
index += partObj.parsedValue.length()
}
return partObjectList
}
void makePartResult(OnePartObject partObj){
if (partObj.isCode){
if (!partObj.isExistCode && !partObj.substitutes){
partObj.parsedValue = (modeExistCodeOnly && partObj.valueCode) ? partObj.partValue : ''
}else{
partObj.parsedValue = partObj.substitutes
}
}else{
partObj.parsedValue = partObj.partValue
}
byte[] bytes = (charset) ? partObj.parsedValue.getBytes(charset) : partObj.parsedValue.getBytes()
partObj.userSetLength = partObj.length
partObj.byteLength = bytes.length
partObj.charLength = partObj.parsedValue.length()
}
OnePartObject generateOnePartObjectForString(String partValue){
return new OnePartObject(
partValue: partValue,
isCode: false,
)
}
OnePartObject generateOnePartObjectForVariable(String partValue, Map<String, Object> variableStringMap, Map<String, Closure> variableClosureMap){
// 1. get String in ${ }
String content
if (variableSign){
content = partValue.replaceFirst("[${variableSign}]", '').replaceFirst('\\{', '').replaceFirst('\\}', '')
}else{
content = partValue.replaceFirst('\\{', '').replaceFirst('\\}', '')
}
validateFunc(content)
// 2. Analysis And Run Function
OnePartObject partObj = new OnePartObject()
partObj.partValue = partValue
partObj.partContent = content
partObj.isCode = true
//- Parse
OnePartObject parsedPartObj = parseCodeContent(partObj, variableStringMap, variableClosureMap)
return parsedPartObj
}
OnePartObject parseCodeContent(String content){
OnePartObject partObj = new OnePartObject()
partObj.partValue = new StringBuilder().append(variableSign).append("{").append(content).append("}").toString()
partObj.partContent = content
partObj.isCode = true
//- Parse
OnePartObject parsedPartObj = parseCodeContent(partObj, this.variableStringMap, this.variableClosureMap)
return parsedPartObj
}
OnePartObject parseCodeContent(OnePartObject partObj, Map<String, Object> variableStringMap, Map<String, Closure> variableClosureMap){
String content = partObj.partContent
List<String> funcs = content?.split(patternToSeperateFuncs)?.toList()
int variableEndIndex = funcs.findIndexOf{ it.indexOf('(') != -1 }
int endIndex = funcs.size() -1
if (variableEndIndex != -1){
String variable = funcs[0..variableEndIndex].join('.')
if (variableEndIndex < endIndex)
funcs = [variable] + funcs[variableEndIndex+1..endIndex]
else
funcs = [content]
}else{
funcs = [content]
}
// If There are no LEFT or RIGHT FUNCTION => Set RIGHT FUNCTION
if ( containsIgnoreCase(funcs, 'LEFT(') || containsIgnoreCase(funcs, 'RIGHT(') ){
}else{
funcs << 'RIGHT()'
}
funcs.eachWithIndex{ String oneFunc, int procIdx ->
// run variable or func
String funcNm = getFuncNameFromOneFunc(oneFunc)
if (funcNm){
String originalCode = funcNm
funcNm = funcNm.toUpperCase()
partObj.funcNm = funcNm
partObj.members = getMemebersFromOneFunc(oneFunc)
//- Check ConditionFunc
if ( getIgnoreCase(conditionFuncMap, funcNm) ) {
if (partObj.modeStream) {
collectStreamContents(partObj, oneFunc)
}else{
try{
runConditionFunc(partObj, variableStringMap, variableClosureMap)
}catch(e){
throw e
}
}
//- Check StreamFunc
}else if ( getIgnoreCase(streamFuncMap, funcNm) ) {
try{
runStreamFunc(partObj, variableStringMap, variableClosureMap)
}catch(e){
throw e
}
// 1) Get Variable's Value
}else if (procIdx == 0){
partObj.originalCode = originalCode
partObj.valueCode = funcNm
getVariableValue(partObj, variableStringMap, variableClosureMap)
// 2) Run Fucntions To Adjust Value
}else if (procIdx > 0){
if (!modeExistFunctionOnly || getIgnoreCase(funcMap, funcNm)){
try{
partObj.funcNameMemberListMap = partObj.funcNameMemberListMap ?: [:]
partObj.funcNameMemberListMap[funcNm] = partObj.members
if (partObj.modeStream){
collectStreamContents(partObj, oneFunc)
}else if (partObj.modeIf){
if (partObj.checkConditionNowSeq())
runFunc(partObj, variableStringMap, variableClosureMap)
}else{
runFunc(partObj, variableStringMap, variableClosureMap)
}
}catch(e){
throw e
}
}else{
throw new Exception(VAR4, new Throwable("[${funcNm}]") )
}
}else{
throw new Exception(VAR4, new Throwable("[${funcNm}]") )
}
}else{
// maybe nothing is not bad
// throw new Exception( ErrorMessage.VAR5.msg, new Throwable("[${partValue}]") )
}
}
return partObj
}
private boolean collectStreamContents(OnePartObject partObj, String oneFunc){
boolean correctLevel = partObj.checkStream()
//1) Stream 영역 내용 수집
if (correctLevel){
//2) Collecting
partObj.virtualRuleBuilderInStream.append(".").append( oneFunc )
}
return correctLevel
}
private String getFuncNameFromOneFunc(String oneFunc){
String funcName = ""
def array = oneFunc.replaceFirst('\\(', ' ').split(' ')
array.eachWithIndex{ String el, int memIdx ->
if (memIdx==0)
funcName = el
}
return funcName
}
private String[] getMemebersFromOneFunc(String oneFunc){
String[] members = []
// get members
Matcher m = Pattern.compile(patternToGetMembers).matcher(oneFunc)
if (m){
String memberString = m[0]
members = memberString.substring(1, memberString.length() -1).split(patternToSeperateMemebers).collect{ it.trim() }
}
return members
}
// String removeSomeVariableCode(String codeRule, String code){
// String removedCode
// return removedCode
// }
//
// String removeSomeVariableCode(String codeRule, List<String> codeList){
// String removedCode
// codeList.each{ String code ->
// removedCode = removeSomeVariableCode(codeRule, code)
// }
// return removedCode
// }
String parseDefaultVariableOnly(String codeRule){
VariableMan variableMan = new VariableMan().setModeExistCodeOnly(true).putVariableClosures(this.getVariableClosureMap())
Object result = variableMan.parse(codeRule)
return result
}
static String getRightReplacement(String replacement){
// This Condition's Logic prevent disapearance \
if (replacement.indexOf('\\') != -1)
replacement = replacement.replaceAll('\\\\','\\\\\\\\')
// This Condition's Logic prevent Error - java.lang.IllegalArgumentException: named capturing group has 0 length name
if (replacement.indexOf('$') != -1)
replacement = replacement.replaceAll('\\$','\\\\\\$')
return replacement
}
static Object parseMember(String member, Map variableStringMap, Map variableClosureMap){
try{
if (member){
if (member.length() > 1
&& (
(member.startsWith(charDoubleQuote) && member.endsWith(charDoubleQuote))
||
(member.startsWith(charSingleQuote) && member.endsWith(charSingleQuote))
)
){
member = member.substring(1, member.length() -1)
}else if (member.isNumber()){
if (member.indexOf(".") != -1){
return Double.parseDouble(member)
}else{
return Integer.parseInt(member)
}
}else{
Closure variableClosure = getIgnoreCase(variableClosureMap, member)
String variableValue = getIgnoreCase(variableStringMap, member)
if (variableClosure != null || variableValue != null){
member = new VariableMan(variableStringMap).setModeExistCodeOnly(false).parse( '${' +member+ '}' )
}
}
}
}catch(e){
logger.error("[VariableMan] faild to parse member", e)
throw e
}
return member
}
static Object parseMemberAsStrict(String member, Map variableStringMap, Map variableClosureMap){
Object memberValue
try{
if (member){
if (member.length() > 1
&& (
(member.startsWith(charDoubleQuote) && member.endsWith(charDoubleQuote))
||
(member.startsWith(charSingleQuote) && member.endsWith(charSingleQuote))
)
){
memberValue = member.substring(1, member.length() - 1)
}else if (member.isNumber()){
if (member.indexOf(".") != -1){
memberValue = Double.parseDouble(member)
}else{
memberValue = Integer.parseInt(member)
}
}else{
Closure variableClosure = getIgnoreCase(variableClosureMap, member)
Object variableValue = getIgnoreCase(variableStringMap, member)
if (containsKeyIgnoreCase(variableStringMap, member)){
memberValue = variableValue
}else if (variableClosure != null || variableValue != null){
memberValue = new VariableMan(variableStringMap).setModeExistCodeOnly(false).parse( '${' +member+ '}' )
}else{
memberValue = null
}
}
}
}catch(e){
logger.error("[VariableMan] faild to parse member", e)
throw e
}
return memberValue
}
/**
* Validation
* @param codeRule
* @return
*/
boolean validateCodeRule(String codeRule) throws Exception{
return validateCodeRule(codeRule, modeMustExistCodeRule)
}
static boolean validateCodeRule(String codeRule, boolean modeMustExistCodeRule) throws Exception{
/* DEVELOPER COMMENT: "It does not matter." */
if (modeMustExistCodeRule && codeRule == null)
throw new NullPointerException()
//- BEFORE
// if ( modeMustExistCodeRule && (!codeRule || !codeRule.trim()) )
// throw new Exception( ErrorMessage.VAR1.msg + "[${codeRule}]" )
if (Pattern.compile('[{]').matcher(codeRule).size() != Pattern.compile('[}]').matcher(codeRule).size())
throw new Exception(VAR6 + "[${codeRule}]" )
return true
}
boolean validateFunc(String func){
/* DEVELOPER COMMENT: "Maybe ${} is not bad" */
// if (!func.trim())
// throw new Exception( ErrorMessage.VAR8.msg + "[${func}]" )
/* DEVELOPER COMMENT: It is not good checking*/
// if (func.matches('.*[)]{1}[^.]{1}.*'))
// throw new Exception( ErrorMessage.VAR5.msg + "[${func}]" )
if (Pattern.compile('[(]').matcher(func).size() != Pattern.compile('[)]').matcher(func).size())
throw new Exception(VAR7 + "[${func}]" )
return true
}
void getVariableValue(OnePartObject partObj, Map<String, Object> variableStringMap, Map<String, Closure> variableClosureMap){
String funcNm = partObj.funcNm
String[] members = partObj.members
//Variable(default) - DATE, RANDOM ...
Closure variableClosure = getIgnoreCase(variableClosureMap, funcNm)
if (variableClosure){
variableClosure(partObj, variableStringMap, variableClosureMap)
partObj.isExistCode = true
return
}
//Variable(custom) - ? (from variableStringMap)
String variableValue = getIgnoreCase(variableStringMap, funcNm)
if (variableValue != null){
partObj.isExistCode = true
partObj.substitutes = variableValue?:''
partObj.bytes = (charset) ? partObj.substitutes.getBytes(charset) : partObj.substitutes.getBytes()
String userSetedValueLengthString = (members) ? parseMember(members[0], variableStringMap, variableClosureMap) : null
if (userSetedValueLengthString && userSetedValueLengthString.matches('[0-9]*') ){
//- Set length
partObj.length = Integer.parseInt(userSetedValueLengthString)
//- Set meta datas
if (partObj.length > 0){
int diff = partObj.length - partObj.bytes.length
if (diff < 0){
// partObj.substitutes = partObj.substitutes.substring(0, partObj.length)
partObj.isOver = true
partObj.overValue = partObj.substitutes
partObj.substitutes = (charset) ? new String(partObj.bytes, 0, partObj.length, charset) : new String(partObj.bytes, 0, partObj.length)
}
}else{
partObj.length = 0
}
}else if (!userSetedValueLengthString){
}else{
throw new Exception(VAR3, new Throwable("[${partObj.partValue}]") )
}
//Variable(?) - (Not Matched)
}else{
partObj.isExistCode = false
partObj.substitutes = ''
partObj.length = (members && members[0]) ? Integer.parseInt(members[0]) : 0
}
}
void runFunc(OnePartObject partObj, Map<String, Object> variableStringMap, Map<String, Closure> variableClosureMap){
Closure closure = getIgnoreCase(this.funcMap, partObj.funcNm)
if (closure)
closure(partObj, variableStringMap, variableClosureMap)
}
void runConditionFunc(OnePartObject partObj, Map<String, Object> variableStringMap, Map<String, Closure> variableClosureMap){
Closure closure = getIgnoreCase(this.conditionFuncMap, partObj.funcNm)
if (closure)
closure(partObj, variableStringMap, variableClosureMap)
}
void runStreamFunc(OnePartObject partObj, Map<String, Object> variableStringMap, Map<String, Closure> variableClosureMap){
Closure closure = getIgnoreCase(this.streamFuncMap, partObj.funcNm)
if (closure)
closure(partObj, variableStringMap, variableClosureMap)
}
/**
* These are Basic Variable
* Watch Below To Add Variable.
*
* Method 1 => New VariableMan(Map)
* Method 2 => New VariableMan().addVariableClosures(Map)
*
* @return
*/
Map<String, Object> getBasicVariableMap(){
InetAddress ip = InetAddress.getLocalHost()
return [
'_os.name': System.getProperty('os.name'),
'_os.version': System.getProperty('os.version'),