-
Notifications
You must be signed in to change notification settings - Fork 10
/
handling.txt
1945 lines (1816 loc) · 96.6 KB
/
handling.txt
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
<%
/** For enabling/disabling debug output */
def verbose = Boolean.parseBoolean(extraParam.verbose)
/** The name of the Java class, which is being masked. */
def targetType = upperCamelCase.call(currentType.name)
/** This stack holds the property (names) visited while traversing the object hierarchy.*/
List<?> propStack = []
/** Indicates that this property is an array. This sack is build while traversing the object hierarchy. */
List<Boolean> propIsArrayStack = []
/**
* Indicates that this property or any of its parents was an array and that we therefore have to process an collection.
* This sack is build while traversing the object hierarchy.
*/
List<Boolean> propIsCollectionStack = []
/**
* Defines overwrites for maskKeys (mapping of property name to associated mask key).
* This may be necessary for e.g. Joined types, where on property holds the Id of the joined object, and another
* property holds the joined object itself (property objectBaseId vs. property objectBase).
*/
Map<String, String> maskKeyOverwrites = [:]
/** For caching the lines generated by the (recursive) closure calls of the model loops! */
List<String> allLines = []
/** Indicates whether the current type is a joined type */
def joined = targetType.endsWith('Joined')
if (verbose) println "type=${currentType.name} javaType=${targetType} joined=$joined"
/** Forward declaration of closure, which calls itself! */
def tuneType
/**
* <b>THIS METHOD ALTERS THE MODEL!!!</b>
* This method tunes the properties of a (complex or reference) type and calls itself recursively if the type
* itself holds properties of other (complex or reference) types.
* Checks for properties with the tag <i>prepLookup</i> and
* <ul>
* <li>joined==true: removes the property completely</li>
* <li>joined==false: removes the suffix Id</li>
* @param type The type to process.
*/
tuneType = { type ->
Closure<Void> action
if (joined) {
action = { prop ->
println "// ATTENTION: Removing lookup property ${prop.name}"
type.properties.remove(prop)
}
} else {
action = { prop ->
def orig = prop.name
def shorten = prop.name.take(prop.name.length() - 2)
println "// ATTENTION: Renaming lookup property from $orig to $shorten"
prop.setName(shorten)
}
}
Collection<?> lookupProps = type.properties.findAll { prop -> prop.hasTag('prepLookup') && prop.name.endsWith('Id') }
type.properties.findAll { prop -> prop.implicitRefIsRefType() && !prop.isSelfReference() } each { prop -> tuneType.call(prop.implicitRef.type) }
type.properties.findAll { prop -> prop.isRefTypeOrComplexType() && !prop.isSelfReference() } each { prop -> tuneType.call(prop.type.type) }
lookupProps.each(action)
}
/**
* Prepares the stacks for running the next loop over the model
*/
def prepareStacks = {
propStack.clear()
propIsArrayStack.clear()
// avoid extra case for handling empty stack!
propIsCollectionStack = [false]
}
/**
* Adds new elements to the stacks
* @param property The property, which is to be visited
*/
def putStacks = { property ->
propStack.add(property)
propIsArrayStack.add(property.type.isArray)
// If either already collection of if this property is an collection.
propIsCollectionStack.add(propIsCollectionStack.last() || property.type.isArray)
}
/**
* Pops the latest elements from the stacks
*/
def popStacks = {
propStack.pop()
propIsArrayStack.pop()
propIsCollectionStack.pop()
}
/**
* Processes a ref or complex property.
* Take the property's type, looks through it properties and returns the one of type UUID.
* That should usually be the entryId or guid!
*/
def findIdProperty = { property ->
def type = property.type.type
List candidates = type.properties.findAll { prop -> prop.type.name() == 'UUID'} // (${type.type.name()})
if (candidates.isEmpty() && type.name == 'ListEntry') {
// ListEntry usually have a StringType property refId (wanted) and text (to be avoided)
candidates.addAll( type.properties.findAll { prop -> prop.type.name() == 'STRING' && prop.name == 'refId'} )
}
/*
assert candidates.size() == 1 : "property=${property.name} type=${type.name} props=${type.properties.collect{ it.name }.join(', ')}"
assert candidates[0].name == 'guid' || candidates[0].name == 'entryId' || candidates[0].name == 'refId' : "property=${property.name} type=${type.name} props=${type.properties.collect{ it.name }.join(', ')}"
*/
return candidates.isEmpty() ? null : candidates[0].name
}
/** Creates a key from current state of propStack, e.g. gis.area */
Closure<String> currentKey = {
return propStack.collect { prop -> prop.name}.join('.')
}
/** Forward declaration of closure, which calls itself! */
def evalDeepNestedListKeys
/**
* Closure which actually looks for the array of ref or complex properties, for which a method removeXXXById(pojo, targetId)
* needs to be created. This closure calls itself recursively!
* @param type The type, which is to be processed
* @param keys The list of keys, which is to be extended while traversing the model.
*/
evalDeepNestedListKeys = { type, List<String> keys ->
// find all ref & complex properties, which are hold in arrays! These are the candidates for the methods removeXXXById(pojo, targetId)
type.properties.findAll{ prop -> prop.isRefTypeOrComplexType() && prop.type.isArray }.each { prop ->
putStacks.call(prop)
def key = currentKey.call()
if (findIdProperty.call(prop)) {
keys.add(key)
} else {
println "ATTENTION: Skip creating removeXXX(pojo, UUID) as property is missing proper ID: type=${currentType.name} key=${key}"
}
popStacks.call()
}
// recurse into all ref & complex properties, which are not hold in arrays!
type.properties.findAll{ prop -> prop.isRefTypeOrComplexType() && !prop.type.isArray }.each { prop ->
putStacks.call(prop)
evalDeepNestedListKeys.call(prop.type.type, keys)
popStacks.call()
}
}
/**
* Closure, which kicks off the search for the keys, which are candidates for the method removeXXXById(pojo, targetId)
* -> find array of ref or complex properties
* @param type The type, which is to be processed
*/
def evalDeepNestedListKeysForType = { type ->
// find keys for method removeXXXById(pojo, targetId) -> find array of ref or complex properties
List<String> keys = []
prepareStacks.call()
evalDeepNestedListKeys.call(type, keys)
return keys
}
/** Forward declaration of closure, which calls itself! */
def evalOtherHandlingKeysForArrays
/**
* Closure which actually looks for the array of ref or complex properties, where another Handling class needs to be called.
* (-> find array of ref or complex properties contained by array of ref or complex type - ignore children unless they lead to another relevant array)
* This closure calls itself recursively!
* @param type The type, which is to be processed
* @param keys The list of keys, which is to be extended while traversing the model.
* @param currDepth The number of array properties, one passed when navigating to the current type
*/
evalOtherHandlingKeysForArrays = { type, List<String> keys, int currDepth ->
// find all ref & complex properties, which are hold in arrays! These are the candidates for the methods removeXXXById(pojo, UUID)
type.properties.findAll{ prop -> prop.isRefTypeOrComplexType() && prop.type.isArray }.each { prop ->
putStacks.call(prop)
def key = currentKey.call()
if (currDepth > 0) {
if (findIdProperty.call(prop)) {
println "Call other handling class for deep nested array property: type=${currentType.name} key=${key}"
keys.add(key)
} else {
println "ATTENTION: Skip calling other Handling classes as array property is missing proper ID: type=${currentType.name} key=${key}"
}
}
popStacks.call()
}
// recurse into all ref & complex properties, array or not!
type.properties.findAll{ prop -> prop.isRefTypeOrComplexType() }.each { prop ->
if (prop.type.isArray) {
currDepth++
}
putStacks.call(prop)
evalOtherHandlingKeysForArrays.call(prop.type.type, keys, currDepth)
if (prop.type.isArray) {
currDepth--
}
popStacks.call()
}
}
/**
* Closure, which kicks off the search for the keys, where another Handling class needs to be called
* -> find array of ref or complex properties contained by array of ref or complex type - ignore children unless they lead to another relevant array
* @param type The type, which is to be processed
*/
def evalOtherHandlingKeysForArraysForType = { type ->
List<String> keys = []
prepareStacks.call()
evalOtherHandlingKeysForArrays.call(type, keys, 0)
return keys
}
/** Forward declaration of closure, which calls itself! */
def evalOtherHandlingKeys
/**
* Closure which actually looks for the array of ref or complex properties, where another Handling class needs to be called.
* (-> find array of ref or complex properties contained by array of ref or complex type, and their ref of complex children)
* This closure calls itself recursively!
* @param type The type, which is to be processed
* @param keys The list of keys, which is to be extended while traversing the model.
* @param currDepth The number of array properties, one passed when navigating to the current type
*/
evalOtherHandlingKeys = { type, List<String> keys, int currDepth ->
// find all ref & complex properties, which are hold in arrays! These are the candidates for the methods removeXXXById(pojo, UUID)
type.properties.findAll{ prop -> prop.isRefTypeOrComplexType() }.each { prop ->
putStacks.call(prop)
def key = currentKey.call()
def isArray = prop.type.isArray
if (isArray && !findIdProperty.call(prop) ) {
println "ATTENTION: Skip calling other Handling classes as array property is missing proper ID: type=${currentType.name} key=${key}"
return
}
if (isArray) {
currDepth++
}
if (currDepth > 1) {
println "Call other handling class for deep nested array property: type=${currentType.name} key=${key}"
keys.add(key)
}
// recurse into all ref & complex properties, array or not!
evalOtherHandlingKeys.call(prop.type.type, keys, currDepth)
if (prop.type.isArray) {
currDepth--
}
popStacks.call()
}
}
/**
* Closure, which kicks off the search for the keys, where another Handling class needs to be called
* -> find array of ref or complex properties contained by array of ref or complex type, and their ref of complex children
* @param type The type, which is to be processed
*/
def evalOtherHandlingKeysForType = { type ->
List<String> keys = []
prepareStacks.call()
evalOtherHandlingKeys.call(type, keys, 0)
return keys
}
/**
* Take a key / chain of property names, and builds a matching property stack. e.g location.streets
*/
def propStackFromKey = { String key ->
List localPropStack = []
def curType = currentType
def curProp
for (String propName : key.split('\\.')) {
curProp = curType.properties.find { it.name == propName }
assert curProp && curProp.isRefTypeOrComplexType() : "propChain=${propChain} propName=${propName}"
localPropStack.add(curProp)
curType = curProp.type.type
}
return localPropStack
}
/**
* Splits the property stack into sub-stacks.
* Each sub-stack starts and ends with an array property.
* Exceptions: the first partition may not start with an array property, the last may not end with an array property.
* Inner array properties are referenced twice: As the last element of sub-stack n and first element of sub-stack n+1
*/
Closure<List<List<?>>> partitionArrayPros = { List<?> fullPropStack ->
final List allList = []
final List currList = []
final Iterator <?> iter = fullPropStack.iterator()
while (iter.hasNext()) {
final def currProp = iter.next()
currList.add(currProp)
if (currProp.type.isArray) {
allList.add(currList.clone())
currList.clear()
currList.add(currProp)
}
}
if (currList.size() > 1) {
allList.add(currList)
}
return allList
}
// Forward declaration of closure, which calls itself!
def evalDeepNestedListChildKeys
/**
* Closure which actually looks for the single ref or complex child of array of ref or complex properties, for which
* a method setXXXById(pojo, targetId, value) needs to be created. This closure calls itself recursively!
* @param type The type, which is to be processed
* @param key Defines the array of ref or complex properties, where single ref or complex child properties are to be found.
* @param listKey2childKey The mapping of array key to child key, which is to be extended while traversing the model.
*/
evalDeepNestedListChildKeys = { type, String key, Map<String, String> listKey2childKey ->
type.properties.findAll{ prop -> prop.isRefTypeOrComplexType() && !prop.type.isArray }.each { prop ->
putStacks.call(prop)
def childKey = currentKey.call()
listKey2childKey.put(key, childKey)
// recurse into all ref & complex properties, which are not hold in arrays!
evalDeepNestedListChildKeys.call(prop.type.type, key, listKey2childKey)
popStacks.call()
}
}
/**
* Closure which kicks off the search for the keys, which are candidates for the method setXXXById(pojo, targetId, value)
* -> find single ref or complex children of array of ref or complex properties
*/
def evalDeepNestedListChildKeysForType = { type, List<String> keys ->
Map<String, String> listKey2childKey = [:]
for (String key : keys) {
prepareStacks.call()
// use key to restore prop stack of array property
propStackFromKey.call(key).each { prop -> putStacks.call(prop) }
// start recursive search for single ref or complex child
assert propStack.last().isRefTypeOrComplexType() && propStack.last().type.isArray : key
evalDeepNestedListChildKeys.call(propStack.last().type.type, key, listKey2childKey)
}
return listKey2childKey
}
/**
* Prints the method boolean addXXX(pojo, additional) associated with one key,
* where the array property is a child of the main type
*/
Closure<String> printAddForKeyShallow = { String key ->
if (verbose) println "// printAddForKeyShallow for key $key"
List<?> localPropStack = propStackFromKey.call(key)
def keyUpper = localPropStack.collect { prop -> upperCamelCase.call(prop.name) }.join('')
def typeNameInner = upperCamelCase.call(localPropStack.last().type.type.name)
def typeName = upperCamelCase.call(currentType.name)
def upperLast = upperCamelCase.call(localPropStack.last().name)
def ret = """
/**
* Tries to add a ${typeNameInner} object to a ${typeName}.
* @param pojo the parent object to extend
* @param additional The ${typeNameInner} object to add to the ${typeName}
* @return <i>True</i>, if the ${typeNameInner} object could be added to the ${typeName},
* <i>false</i> otherwise.
*/
public static boolean add${keyUpper}(final ${typeName} pojo, final ${typeNameInner} additional) {
if (check${keyUpper}Exists(pojo)) {
get${keyUpper}(pojo).add(additional);
return true;
}
List<${typeNameInner}> list = new ArrayList<>();
list.add(additional);
pojo.set${upperLast}(list);
return true;
}"""
return ret
}
/**
* Prints the method boolean addXXX(pojo, additional) associated with one key
* of a deep nested array property.
*/
Closure<String> printAddForKeyDeep = { String key ->
if (verbose) println "// printAddForKeyDeep for key $key"
List<?> localPropStack = propStackFromKey.call(key)
def keyUpper = localPropStack.collect { prop -> upperCamelCase.call(prop.name) }.join('')
def typeNameInner = upperCamelCase.call(localPropStack.last().type.type.name)
def typeName = upperCamelCase.call(currentType.name)
List<?> parentStack = localPropStack.clone()
parentStack.pop()
def keyUpperParent = parentStack.collect { prop -> upperCamelCase.call(prop.name) }.join('')
def upperSecondLast = upperCamelCase.call(parentStack.last().name)
def upperLast = upperCamelCase.call(localPropStack.last().name)
def ret = """
/**
* Tries to add a ${typeNameInner} object to a ${typeName}.
* @param pojo the parent object to extend
* @param additional The ${typeNameInner} object to add to the ${typeName}
* @return <i>True</i>, if the ${typeNameInner} object could be added to the ${typeName},
* <i>false</i> otherwise.
*/
public static boolean add${keyUpper}(final ${typeName} pojo, final ${typeNameInner} additional) {
if (check${keyUpper}Exists(pojo)) {
get${keyUpper}(pojo).add(additional);
return true;
}if (!check${keyUpperParent}Exists(pojo)) {
return false;
}
List<${typeNameInner}> list = new ArrayList<>();
list.add(additional);
pojo.get${upperSecondLast}().set${upperLast}(list);
return true;
}"""
return ret
}
/**
* Prints the method boolean addXXX(pojo, additional) associated with one key.
* Delegates to either to printAddForKeyShallow or to printAddForKeyDeep
*/
Closure<String> printAddForKey = { String key ->
int depth = key.split('\\.').size()
if (depth == 1) {
return printAddForKeyShallow.call(key)
}
return printAddForKeyDeep.call(key)
}
/**
* Prints the method void addXXX(pojo, additional) throws MissingXXXException associated with one key.
*/
Closure<String> printAddForKeyThrows = { String key ->
/*
public static void addObjectBaseTags(final JunctionJoined pojo, final ListEntry additional)
throws MissingParentException, MissingTargetException {
ensureObjectBaseTagsExists(pojo, false);
getObjectBaseTags(pojo).add(additional);
}
*/
if (verbose) println "// printAddForKeyThrows for key $key"
List<?> localPropStack = propStackFromKey.call(key)
def keyUpper = localPropStack.collect { prop -> upperCamelCase.call(prop.name) }.join('')
def typeNameInner = upperCamelCase.call(localPropStack.last().type.type.name)
def typeName = upperCamelCase.call(currentType.name)
def ret = """
/**
* Adds a ${typeNameInner} object to a ${typeName}.
* @param pojo the parent object to extend
* @param additional The ${typeNameInner} object to add to the ${typeName}
* @throws MissingTargetException if the attribute holding the ${typeNameInner} objects is null
* @throws MissingParentException if any parent of the attribute holding the ${typeNameInner} objects is missing.
*/
public static void add${keyUpper}(final ${typeName} pojo, final ${typeNameInner} additional)
throws MissingParentException, MissingTargetException {
ensure${keyUpper}Exists(pojo, false);
get${keyUpper}(pojo).add(additional);
}"""
return ret
}
/**
* Prints the method void getXXX(pojo, UUID, replacement) throws MissingXXXException associated with one key
* of a nested array property.
*/
Closure<String> printGetForKeyThrows = { String key ->
/*
public static AddressPerson getAddressPersonsById(final JunctionContact pojo, final UUID targetId)
throws MissingParentException, MissingTargetException {
final ListIterator<AddressPerson> iter = getAddressPersonsThrows(pojo).listIterator();
while (iter.hasNext()) {
if (iter.next().getAddressId().equals(targetId)) {
return iter.previous();
}
}
throw new MissingTargetException("address.persons", targetId);
}
*/
List<?> localPropStack = propStackFromKey.call(key)
def keyUpper = localPropStack.collect { prop -> upperCamelCase.call(prop.name) }.join('')
def typeNameInner = upperCamelCase.call(localPropStack.last().type.type.name)
def typeName = upperCamelCase.call(currentType.name)
// usually one of entryId, guid or refId!
def idProp = upperCamelCase.call(findIdProperty.call(localPropStack.last()))
def ret = """
/**
* Returns a specific ${typeNameInner} object from a ${typeName}.
* @param pojo The ${typeName} object to process
* @param targetId The ID of the ${typeNameInner}, which is to be returned.
* @throws MissingTargetException if no ${typeNameInner} of that id was found and subsequently returned,
* @throws MissingParentException if the attribute holding the ${typeNameInner} objects or any of its parent objects is
* missing.
*/
public static ${typeNameInner} get${keyUpper}ById(final ${typeName} pojo, final UUID targetId)
throws MissingParentException, MissingTargetException {
final ListIterator<${typeNameInner}> iter = get${keyUpper}Throws(pojo).listIterator();
while (iter.hasNext()) {
if (iter.next().get${idProp}().equals(targetId)) {
return iter.previous();
}
}
throw new MissingTargetException("${key}", targetId);
}"""
return ret
}
/**
* Prints the method replaceXXX(pojo, UUID, replacement) associated with one key
* of a nested array property.
*/
Closure<String> printReplaceForKey = { String key ->
List<?> localPropStack = propStackFromKey.call(key)
def keyUpper = localPropStack.collect { prop -> upperCamelCase.call(prop.name) }.join('')
def typeNameInner = upperCamelCase.call(localPropStack.last().type.type.name)
def typeName = upperCamelCase.call(currentType.name)
// usually one of entryId, guid or refId!
def idProp = upperCamelCase.call(findIdProperty.call(localPropStack.last()))
def ret = """
/**
* Tries to replace a specific ${typeNameInner} object of a ${typeName}.
* @param pojo The ${typeName} object to process
* @param targetId The ID of the ${typeNameInner}, which is to be replaced.
* @param replacement The ${typeNameInner} object to assign to the ${typeName}
* @return <i>True</i>, if a ${typeNameInner} of that id was found and subsequently replaced,
* <i>false</i> if no object with that id could be found and therefore replaced.
*/
public static boolean replace${keyUpper}ById(final ${typeName} pojo, final UUID targetId, final ${typeNameInner} replacement) {
final ListIterator<${typeNameInner}> iter = get${keyUpper}(pojo).listIterator();
while (iter.hasNext()) {
if (iter.next().get${idProp}().equals(targetId)) {
iter.set(replacement);
return true;
}
}
return false;
}"""
return ret
}
/**
* Prints the method void replaceXXXById(pojo, targetId, replacement) throws MissingXXXException associated with one key
* of a nested array property.
*/
Closure<String> printReplaceForKeyThrows = { String key ->
/*
public static void replaceObjectBaseTagsById(final JunctionJoined pojo, final UUID targetId,
final ListEntry replacement) throws MissingParentException, MissingTargetException {
final ListIterator<ListEntry> iter = getObjectBaseTagsThrows(pojo).listIterator();
while (iter.hasNext()) {
if (iter.next().getRefId().equals(targetId)) {
iter.set(replacement);
return;
}
}
throw new MissingTargetException("objectBase.tags", targetId);
}
*/
List<?> localPropStack = propStackFromKey.call(key)
def keyUpper = localPropStack.collect { prop -> upperCamelCase.call(prop.name) }.join('')
def typeNameInner = upperCamelCase.call(localPropStack.last().type.type.name)
def typeName = upperCamelCase.call(currentType.name)
// usually one of entryId, guid or refId!
def idProp = upperCamelCase.call(findIdProperty.call(localPropStack.last()))
def ret = """
/**
* Replaces a specific ${typeNameInner} object of a ${typeName}.
* @param pojo The ${typeName} object to process
* @param targetId The ID of the ${typeNameInner}, which is to be replaced.
* @param replacement The ${typeNameInner} object to assign to the ${typeName}
* @throws MissingTargetException if no ${typeNameInner} of that id was found and subsequently replaced,
* @throws MissingParentException if the attribute holding the ${typeNameInner} objects or any of its parent objects is
* missing.
*/
public static void replace${keyUpper}ById(final ${typeName} pojo, final UUID targetId,
final ${typeNameInner} replacement) throws MissingParentException, MissingTargetException {
final ListIterator<${typeNameInner}> iter = get${keyUpper}Throws(pojo).listIterator();
while (iter.hasNext()) {
if (iter.next().get${idProp}().equals(targetId)) {
iter.set(replacement);
return;
}
}
throw new MissingTargetException("${key}", targetId);
}"""
return ret
}
/**
* Prints the method void setXXXById(pojo, targetId, value) throws MissingXXXException associated for a the single ref
* or complex child of an arrays of ref or complex properties
* @param keyArray the key associated with an array of ref or complex property
* @param keyChild the key associated with the the single ref or complex child of the array property.
*/
Closure<String> printSetForKeyThrows = { String keyArray, String keyChild ->
/*
public static void setAddressPersonsContactById(final JunctionContact pojo, final UUID targetId,
final ContactData value) throws MissingParentException, MissingTargetException {
final ListIterator<AddressPerson> iter = getAddressPersonsThrows(pojo).listIterator();
while (iter.hasNext()) {
iter.previous().setContact(value);
// TODO Add missing parents check here in case of deep nested value property!
// Or introduce AddressPersonHandling and utilize here!
// AddressPersonHandling.setContact(iter.previous(), value);
return;
}
throw new MissingTargetException("address.persons", targetId);
}
*/
List<?> propStackChild = propStackFromKey.call(keyChild)
List<?> propStackArray = propStackFromKey.call(keyArray)
List<?> propStackInner = propStackChild.subList(propStackArray.size(), propStackChild.size())
def keyUpper = propStackChild.collect { prop -> upperCamelCase.call(prop.name) }.join('')
def keyUpperIntermediate = propStackArray.collect { prop -> upperCamelCase.call(prop.name) }.join('')
// in case of deep nested child
def keyUpperInner = propStackInner.collect { prop -> upperCamelCase.call(prop.name) }.join('')
// in case of shallow child
def setterName = upperCamelCase.call(propStackChild.last().name)
def typeName = upperCamelCase.call(currentType.name)
def typeNameIntermediate = upperCamelCase.call(propStackArray.last().type.type.name)
def typeNameInner = upperCamelCase.call(propStackChild.last().type.type.name)
// usually one of entryId, guid or refId!
def idProp = upperCamelCase.call(findIdProperty.call(propStackArray.last()))
def ret = """
/**
* Replaces the ${typeNameInner} of a specific ${typeNameIntermediate} object of a ${typeName}.
* @param pojo The ${typeName} object to process
* @param targetId The ID of the ${typeNameIntermediate}, which is to be altered.
* @param value The ${typeNameInner} object to assign to the ${typeNameIntermediate}
* @throws MissingTargetException if no ${typeNameIntermediate} of that id was found and subsequently altered,
* @throws MissingParentException if
* <ul>
* <li> the attribute holding the ${typeNameIntermediate} objects or any of its parent objects is missing.</li>
* <li> the attribute holding the ${typeNameInner} objects or any of its parent objects is missing.</li>
* </ul>
*/
public static void set${keyUpper}ById(final ${typeName} pojo, final UUID targetId,
final ${typeNameInner} value) throws MissingParentException, MissingTargetException {
final ListIterator<${typeNameIntermediate}> iter = get${keyUpperIntermediate}Throws(pojo).listIterator();
while (iter.hasNext()) {
if (iter.next().get${idProp}().equals(targetId)) {
// in case of shallow ref or complex child:
iter.previous().set${setterName}(value);
// in case of deep nested ref or complex child:
// TODO Add missing parents check here in case of deep nested value property!
// Or introduce ${typeNameIntermediate}Handling and utilize here!
// ${typeNameIntermediate}Handling.set${keyUpperInner}(iter.previous(), value);
return;
}
}
throw new MissingTargetException("${keyArray}", targetId);
}"""
return ret
}
/**
* Prints the method removeXXX(pojo, UUID) associated with one key
* of a nested array property.
*/
Closure<String> printRemoveForKey = { String key ->
List<?> localPropStack = propStackFromKey.call(key)
def keyUpper = localPropStack.collect { prop -> upperCamelCase.call(prop.name) }.join('')
def typeNameInner = upperCamelCase.call(localPropStack.last().type.type.name)
def typeName = upperCamelCase.call(currentType.name)
// usually one of entryId, guid or refId!
def idProp = upperCamelCase.call(findIdProperty.call(localPropStack.last()))
def ret = """
/**
* Tries to remove a specific ${typeNameInner} object from a ${typeName}.
* @param pojo The object to process
* @param targetId The ID of the ${typeNameInner}, which is to be removed.
* @return <i>True</i>, if a ${typeNameInner} of that id was found and subsequently removed,
* <i>false</i> if no object with that id could be found and therefore removed.
*/
public static boolean remove${keyUpper}ById(${typeName} pojo, UUID targetId) {
final Iterator<${typeNameInner}> iter = get${keyUpper}(pojo).iterator();
while (iter.hasNext()) {
if (iter.next().get${idProp}().equals(targetId)) {
iter.remove();
return true;
}
}
return false;
}"""
return ret
}
/**
* Prints the method void removeXXX(pojo, UUID) associated with one key
* of a nested array property.
*/
Closure<String> printRemoveForKeyThrows = { String key ->
/*
public static void removeLocationStreetsById(final JunctionJoined pojo, final UUID targetId)
throws MissingParentException, MissingTargetException {
final Iterator<JunctionLocationStreetsItem> iter = getLocationStreetsThrows(pojo).iterator();
while (iter.hasNext()) {
if (iter.next().getEntryId().equals(targetId)) {
iter.remove();
return;
}
}
throw new MissingTargetException("location.streets", targetId);
}
*/
List<?> localPropStack = propStackFromKey.call(key)
def keyUpper = localPropStack.collect { prop -> upperCamelCase.call(prop.name) }.join('')
def typeNameInner = upperCamelCase.call(localPropStack.last().type.type.name)
def typeName = upperCamelCase.call(currentType.name)
// usually one of entryId, guid or refId!
def idProp = upperCamelCase.call(findIdProperty.call(localPropStack.last()))
def ret = """
/**
* Removes a specific ${typeNameInner} object from a ${typeName}.
* @param pojo The object to process
* @param targetId The ID of the ${typeNameInner}, which is to be removed.
* @throws MissingTargetException if no ${typeNameInner} of that id was found and subsequently removed,
* @throws MissingParentException if the attribute holding the ${typeNameInner} objects or any of its parent objects is
* missing.
*/
public static void remove${keyUpper}ById(final ${typeName} pojo, final UUID targetId)
throws MissingParentException, MissingTargetException {
final Iterator<${typeNameInner}> iter = get${keyUpper}Throws(pojo).iterator();
while (iter.hasNext()) {
if (iter.next().get${idProp}().equals(targetId)) {
iter.remove();
return;
}
}
throw new MissingTargetException("${key}", targetId);
}"""
return ret
}
/**
* Actually creates the case of the getValue method for properties of a complex or reference class.
* @param prop The property to process
* @param lines Where the created lines of code are to be added.
*/
def createGetValueSimple = { property, List<String> lines ->
def parentCollection = propIsCollectionStack.last()
def parentProp = propStack.empty ? null : propStack.last()
def propStackParent = []; propStackParent.addAll(propStack)
putStacks.call(property)
def key = propStack.collect {prop -> prop.name}.join('.')
def suffix = !joined && property.hasTag('prepLookup') ? 'Id' : ''
if (verbose) println "type=${currentType.name} key=${key} parentCollection=${parentCollection} parCollClass=${parentCollection.class.getName()}"
if (propStack.size() == 1) {
// in case of normal type and tag 'prepLookup' add suffix Id to method name -> getObjectBaseId()!
lines.add(""" case "${key}":
return pojo.get${firstUpperCase.call(property.name)}${suffix}();""" )
} else if (parentCollection) {
// parent is collection: stream collection, map to value, collect(Collectors.toList())
/* Example
case "objectBase.gis.area.points.lon":
return getObjectBaseGisAreaPoints(target).stream().map(p -> p.getLon()).collect(Collectors.toList());
*/
String methodName = propStackParent.collect{ prop -> upperCamelCase.call(prop.name) }.join('')
String parentChar = parentProp.name.take(1)
lines.add(""" case "${key}":
return get${methodName}(pojo).stream().map(${parentChar} -> ${parentChar}.get${upperCamelCase.call(property.name)}${suffix}()).collect(Collectors.toList());""")
// lines.add(""" case "${propStack.collect {prop -> prop.name}.join('.')}": return null; // TODO""" )
} else {
// parent not a collection: simple parent null check and return value
/* Example:
case "objectBase.gis.area.projection":
if (checkObjectBaseGisAreaExists(pojo)) {
return pojo.getObjectBase().getGis().getArea().getProjection();
} else {
return null;
}
*/
String methodName = propStackParent.collect{ prop -> upperCamelCase.call(prop.name) }.join('')
String getChain = propStack.collect{ prop -> upperCamelCase.call(prop.name) }.join('().get')
lines.add(""" case "${key}":
if (check${methodName}Exists(pojo)) {
return pojo.get${getChain}${suffix}();
} else {
return null;
}""" )
}
popStacks.call()
}
/** Forward declaration of closure, which calls itself! */
def createGetValueForType
/**
* Creates the case statements of the getValue method for a certain type, calls itself recursively for reference
* and complex types!
* @param type The type to process
* @param lines Where the created lines of code are to be added.
*/
createGetValueForType = { type, List<String> lines ->
filterProps.call(type, [refComplex:false]).each { prop ->
if (verbose) println "// createGetValueForType/RefTypeOrComplexType=false: type=${type.name} prop=${prop.name}"
createGetValueSimple.call(prop, lines)
}
filterProps.call(type, [refComplex:true]).each { prop ->
createGetValueSimple.call(prop, lines)
// recursive call!
putStacks.call(prop)
createGetValueForType.call(prop.type.type, lines)
popStacks.call()
}
}
// Forward declaration of closure, which calls itself!
Closure<Integer> createEnsureMatchingForType
/**
* Creates the content of the method ensureMatchingEntryId for a certain type, calls itself recursively for reference
* and complex types!
* @param type The type to process
* @param lines Where the created lines of code are to be added.
*/
createEnsureMatchingForType = { type, List<String> lines, int idx ->
// Track the number of increments of idx!
int incCount = 0
if (propIsCollectionStack.last()) {
def pProp = propStack.last()
boolean parentHasEntryId = pProp.isRefTypeOrComplexType() && pProp.type.type.properties.collect { prop2 -> prop2.name }.contains('entryId')
if (parentHasEntryId) {
/* Example
final Iterator<AddressPerson> sourceIter1 = getAddressPersons(source).iterator();
final Iterator<AddressPerson> targetIter1 = getAddressPersons(target).iterator();
while(sourceIter1.hasNext()) {
targetIter1.next().setEntryId(sourceIter1.next().getEntryId());
}
*/
lines.add(" // found pProp=${pProp.name} type=${upperCamelCase.call(type.name)}")
def jType = upperCamelCase.call(type.name)
def methodName = propStack.collect { prop -> upperCamelCase.call(prop.name) }.join('')
idx += 1
incCount += 1
lines.add(
""" final Iterator<${jType}> sourceIter${idx} = get${methodName}(source).iterator();
final Iterator<${jType}> targetIter${idx} = get${methodName}(target).iterator();
while(sourceIter${idx}.hasNext()) {
targetIter${idx}.next().setEntryId(sourceIter${idx}.next().getEntryId());
}""")
}
}
filterProps.call(type, [refComplex:true]).each { prop ->
// recursive call!
putStacks.call(prop)
// idx may have been incremented 0 to n times by the recursive call!
int recIncCount = createEnsureMatchingForType.call(prop.type.type, lines, idx)
popStacks.call()
idx += recIncCount
incCount += recIncCount
}
return incCount
}
// Forward declaration of closure, which calls itself!
def printCheckExistsForType
/**
* Prints the methods checkXXXExists(target) for a certain type, calls itself recursively for reference and complex types!
* @param type The type to process
*/
printCheckExistsForType = { type ->
int size = propIsCollectionStack.size()
if ( size > 2 && propIsCollectionStack.get(size-2)) {
// can not check for null in children of array property -> stop creating more methods checkXXXExists()!
return
}
if (!propStack.isEmpty()) {
/*
public static boolean checkObjectBaseGisAreaExists(JunctionNumberJoined target) {
return target.getObjectBase() != null
&& target.getObjectBase().getGis() != null
&& target.getObjectBase().getGis().getArea() != null;
}
*/
def checkMethodPart = propStack.collect{ upperCamelCase.call(it.name) }.join('') // e.g. AddressPersonsContact
// create longest getter call chain and then process it from one to all elements.
List lines = []
List getCalls = propStack.collect { "get${upperCamelCase.call(it.name)}()"}
for (int i = 0; i < getCalls.size(); i++) {
def cond = getCalls.subList(0, i+1).join('.')
lines.add("target.${cond} != null")
}
def conditions = lines.join('\n && ')
%>
/**
* @param target The object, which is to be processed.
* @return <i>True</i>, if the attribute and all its parents exist, <i>false</i> otherwise.
*/
public static boolean check${checkMethodPart}Exists(${targetType} target) {
return ${conditions};
}
<%
}
// type.properties.findAll { prop -> return prop.isRefTypeOrComplexType() }.each { prop ->
filterProps.call(type, [refComplex:true]).each { prop ->
// recursive call!
putStacks.call(prop)
printCheckExistsForType.call(prop.type.type)
popStacks.call()
}
}
// Forward declaration of closure, which calls itself!
def printEnsureExistsForType
/**
* Prints the methods ensureXXXExists(target, boolean) for a certain type, calls itself recursively for reference and complex types!
* @param type The type to process
*/
printEnsureExistsForType = { type ->
int size = propIsCollectionStack.size()
if ( size > 2 && propIsCollectionStack.get(size-2)) {
// can not check for null in children of array property -> stop creating more methods checkXXXExists()!
return
}
if (!propStack.isEmpty()) {
/*
public static void ensureObjectBaseGisAreaPointsExists(JunctionJoined target, boolean isParent)
throws MissingParentException, MissingTargetException {
ensureObjectBaseGisAreaExists(target, true);
if (target.getObjectBase().getGis().getArea().getPoints() == null) {
if (isParent) {
throw new MissingParentException("objectBase.gis.area.points");
}
throw new MissingTargetException("objectBase.gis.area.points");
}
}
*/
def ensureMethodPart = propStack.collect{ upperCamelCase.call(it.name) }.join('') // e.g. AddressPersonsContact
def key = currentKey.call()
List<String> getCalls = propStack.collect { "get${upperCamelCase.call(it.name)}()"}
def getCall = getCalls.join('.')
def parentCall
int stackDim = propStack.size()
if (stackDim == 1) {
parentCall = ''
} else {
def ensureMethodPartParent = propStack.subList(0, stackDim-1).collect{ upperCamelCase.call(it.name) }.join('')
parentCall = "\n ensure${ensureMethodPartParent}Exists(target, false);"
}
%>
/**
* Before performing an operation on an attribute like e.g. replacing or removing it, this method checks whether
* that attribute and all its parent objects actually exist.
* @param target The object, which is to be processed.
* @param isParent Indicates whether the attribute is regarded as the target of the operation. This parameter
* controls, which Exception is emitted when all parent objects are available but the attribute itself is
* missing!
* @throws MissingTargetException If the attribute is missing and parameter <i>isParent</i> indicates that it is
* regarded as the target of the operation.
* @throws MissingParentException If either any of the parent objects of the attribute is missing or if the
* attribute itself is missing and parameter <i>isParent</i> indicates that the attribute is not
* regarded as the target of the operation.
*/
public static void ensure${ensureMethodPart}Exists(${targetType} target, boolean isParent)
throws MissingParentException, MissingTargetException {${parentCall}
if (target.${getCall} == null) {
if (isParent) {
throw new MissingParentException("${key}");
}
throw new MissingTargetException("${key}");
}
}
<%
}
// type.properties.findAll { prop -> return prop.isRefTypeOrComplexType() }.each { prop ->
filterProps.call(type, [refComplex:true]).each { prop ->
// recursive call!
putStacks.call(prop)
printEnsureExistsForType.call(prop.type.type)
popStacks.call()
}
}
// Forward declaration of closure, which calls itself!
def printGetForType
/**
* Prints the methods getXXX(target) (returning a list of objects) for a certain type, calls itself recursively for
* reference and complex types!
* @param type The type to process
*/
printGetForType = { type ->
if (propIsCollectionStack.last()) {
// Example for key address.persons.contact where persons is the only array type
// In case of multiple array types use .flatMap() for 2. to last array type!
// We can not check for null references for objects in the object tree after hitting the first array property.
// ->
// A: the method checkXXXExists only checks for null references up to the first array property.
// B: do use Stream.filter() with a predicate for filtering out the null references!
/*
public static List<ContactData> getAddressPersonsContact(JunctionContactJoined target) {
if (checkAddressPersonsExists(target)) {
return target.getAddress().getPersons().stream()
.filter(p -> p.getContact() != null)
.map(p -> p.getContact())
.collect(Collectors.toList());
}
return Collections.emptyList();
}
*/
def methodName = propStack.subList(0, propStack.size()).collect { upperCamelCase.call(it.name) }.join('') // e.g. AddressPersonsContact
int maxCheckProp = propIsCollectionStack.last() ? propIsCollectionStack.indexOf(Boolean.TRUE) : propStack.size() // The index of the first entry of propIsCollectionStack indicating value collection