forked from zstackio/zstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGoApiTemplate.groovy
More file actions
1525 lines (1383 loc) · 60.7 KB
/
GoApiTemplate.groovy
File metadata and controls
1525 lines (1383 loc) · 60.7 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
package scripts
import org.zstack.header.query.APIQueryMessage
import org.zstack.header.rest.RestRequest
import org.zstack.rest.sdk.SdkFile
import org.zstack.rest.sdk.SdkTemplate
import org.zstack.utils.Utils
import org.zstack.utils.logging.CLogger
import java.lang.reflect.Field
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
/**
* Go SDK API Template Generator
*/
class GoApiTemplate implements SdkTemplate {
private static final CLogger logger = Utils.getLogger(GoApiTemplate.class)
private Class<?> apiMsgClazz
private RestRequest at
private String path
private Class responseClass
private String replyName
private SdkTemplate inventoryGenerator
private String actionType
private String resourceName
private String clzName
// For Query APIs, store the inventory class
private Class<?> queryInventoryClass
// Store the field name of the inventory in the response class (e.g. "inventory", "vmInventory")
private String inventoryFieldName
// Track if different parts of the API have been grouped into consolidated files
boolean isActionGrouped = false
boolean isViewGrouped = false
boolean isParamGrouped = false
// Track generated files to avoid duplicates
private static Set<String> generatedParamFiles = new HashSet<>()
private static Set<String> generatedActionFiles = new HashSet<>()
private static Set<String> generatedViewFiles = new HashSet<>()
// Track known inventory classes for validation
private static Set<Class<?>> knownInventoryClasses = null
// Track APIs that have been grouped by GoInventory to avoid individual file generation
static Set<String> groupedApiNames = new HashSet<>()
// LongJob mappings (provided by GoInventory)
private static Map<Class, Class> longJobMappings = new HashMap<>()
// Track APIs that should be skipped during generation
private static Set<String> skippedApis = new HashSet<>()
GoApiTemplate(Class apiMsgClass, SdkTemplate inventoryGenerator) {
try {
apiMsgClazz = apiMsgClass
this.inventoryGenerator = inventoryGenerator
at = apiMsgClazz.getAnnotation(RestRequest.class)
if (at == null) {
logger.warn("[GoSDK] Class ${apiMsgClazz.name} is missing @RestRequest annotation")
return
}
String rawPath = at.path()
if (rawPath == null || rawPath == "null") {
String[] opts = at.optionalPaths()
if (opts != null && opts.length > 0) {
path = opts[0]
} else {
logger.warn("[GoSDK] API ${apiMsgClazz.name} has no path or optionalPaths")
path = "/unknown"
}
} else {
path = rawPath
}
responseClass = at.responseClass()
if (responseClass == null || responseClass == org.zstack.header.rest.RestResponse.class) {
org.zstack.header.rest.RestResponse res = apiMsgClazz.getAnnotation(org.zstack.header.rest.RestResponse.class)
if (res != null) {
responseClass = res.value()
}
}
if (responseClass != null) {
replyName = responseClass.simpleName.replaceAll('^API', '').replaceAll('Reply$', '').replaceAll('Event$', '')
} else {
logger.warn("[GoSDK] Could not determine responseClass for " + apiMsgClazz.name)
replyName = "UnknownResponse"
}
// Only strip API prefix and Msg suffix, keep Action to avoid name collisions
// e.g. APIQueryMonitorTriggerActionMsg -> QueryMonitorTriggerAction
clzName = apiMsgClazz.simpleName.replaceAll('^API', '').replaceAll('Msg$', '')
parseActionAndResource()
logger.warn("[GoSDK] Parsed API: ${apiMsgClazz.simpleName} -> Action=${actionType}, Resource=${resourceName}")
// Find the inventory class if available (for both Query and Action APIs)
queryInventoryClass = findInventoryClass()
logger.warn("[GoSDK] Processing API: " + clzName + " -> action=" + actionType + ", resource=" + resourceName + ", response=" + responseClass?.simpleName)
} catch (Throwable e) {
logger.error("[GoSDK] CRITICAL ERROR constructing GoApiTemplate for ${apiMsgClass.name}: ${e.class.name}: ${e.message}", e)
throw e
}
}
RestRequest getAt() {
return at
}
String getActionType() {
return actionType
}
String getResourceName() {
return resourceName
}
Class<?> getQueryInventoryClass() {
return queryInventoryClass
}
Class<?> getResponseClass() {
return responseClass
}
/**
* Return all client method names this template may emit, for deduplication.
*/
Set<String> getGeneratedMethodNames() {
def names = new LinkedHashSet<String>()
names.add(clzName)
// Query APIs always generate both Get and Page helpers
if (isQueryMessage()) {
String getMethodName = clzName.replaceFirst('^Query', 'Get')
names.add(getMethodName)
String pageMethodName = clzName.replaceFirst('^Query', 'Page')
names.add(pageMethodName)
}
if (supportsAsync() && shouldGenerateAsync()) {
names.add("${clzName}Async")
}
return names
}
boolean isQueryMessage() {
return APIQueryMessage.class.isAssignableFrom(apiMsgClazz)
}
Class<?> getApiMsgClazz() {
return apiMsgClazz
}
String getParamStructName() {
return clzName + "Param"
}
String getDetailParamStructName() {
return clzName + "ParamDetail"
}
/**
* Set known inventory classes for validation
*/
static void setKnownInventoryClasses(Set<Class<?>> inventories) {
knownInventoryClasses = inventories
logger.warn("[GoSDK] Registered " + (inventories?.size() ?: 0) + " inventory classes")
}
/**
* Set LongJob mappings (called by GoInventory)
*/
static void setLongJobMappings(Map<Class, Class> mappings) {
longJobMappings = mappings
logger.warn("[GoSDK] Registered ${mappings.size()} LongJob mappings")
}
/**
* Check if current API supports async operation
*/
private boolean supportsAsync() {
if (apiMsgClazz == null) return false
return longJobMappings.containsKey(apiMsgClazz)
}
/**
* Get list of skipped APIs
*/
static Set<String> getSkippedApis() {
return skippedApis
}
/**
* Check if a view class is available
*/
private boolean isViewAvailable(Class<?> viewClass) {
if (viewClass == null) {
return false
}
// Check if it's an Inventory class or a Reply class
if (knownInventoryClasses != null && knownInventoryClasses.contains(viewClass)) {
return true
}
// Reply classes should always be available as we generate them
if (viewClass.simpleName.endsWith("Reply") || viewClass.simpleName.endsWith("Event")) {
return true
}
return false
}
/**
* Check if API class has valid parameter fields (excluding inherited base fields)
*/
private boolean hasApiParams() {
if (apiMsgClazz == null) {
return false
}
try {
def fields = apiMsgClazz.getDeclaredFields()
// Filter out synthetic, static fields and common inherited fields
def validFields = fields.findAll { field ->
!java.lang.reflect.Modifier.isStatic(field.modifiers) &&
!field.synthetic &&
!field.name.startsWith('__') &&
field.name != 'session' &&
field.name != 'timeout' &&
field.name != 'commandTimeout'
}
boolean result = validFields.size() > 0
if (!result) {
logger.warn("[GoSDK] ${apiMsgClazz.simpleName} has NO valid parameter fields")
}
return result
} catch (Exception e) {
logger.warn("[GoSDK] Error checking params for ${apiMsgClazz.simpleName}: ${e.message}")
return true // Default to true if can't determine
}
}
private Class<?> findInventoryClass() {
inventoryFieldName = null
if (responseClass == null) return null
logger.debug("[GoSDK] Finding inventory class for API: " + clzName + " (response=" + responseClass?.simpleName + ")")
try {
// 1. Try to find 'inventory' field (for single resource return)
try {
Field inventoryField = responseClass.getDeclaredField("inventory")
if (inventoryField != null) {
Class<?> fieldType = inventoryField.getType()
// If inventory is a collection or map, skip unwrap to avoid List/MapView pointer mismatch
if (Collection.class.isAssignableFrom(fieldType) || Map.class.isAssignableFrom(fieldType)) {
logger.warn("[GoSDK] Inventory field for " + clzName + " is a collection/map, skip unwrap")
inventoryFieldName = null
// Try to unwrap generic element/value only if it's a concrete Inventory class
if (inventoryField.getGenericType() instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) inventoryField.getGenericType()
Type[] args = pt.getActualTypeArguments()
if (args != null && args.length > 0) {
Type candidate = args.length > 1 ? args[1] : args[0]
if (candidate instanceof Class && ((Class<?>) candidate).isAnnotationPresent(org.zstack.header.search.Inventory.class)) {
return (Class<?>) candidate
}
}
}
return null
}
logger.warn("[GoSDK] Found inventory field for " + clzName + ": " + fieldType.simpleName)
inventoryFieldName = "inventory"
return fieldType
}
} catch (NoSuchFieldException e) {
// ignore
}
// 2. Try to find 'inventories' field (for query/list return)
try {
Field inventoriesField = responseClass.getDeclaredField("inventories")
if (inventoriesField != null) {
def genericType = inventoriesField.getGenericType()
if (genericType != null && genericType instanceof ParameterizedType) {
def paramType = (ParameterizedType) genericType
def actualTypes = paramType.getActualTypeArguments()
if (actualTypes != null && actualTypes.length > 0) {
def typeArg = actualTypes[0]
if (typeArg instanceof Class) {
logger.warn("[GoSDK] Found inventories element class for " + clzName + ": " + ((Class<?>) typeArg).simpleName)
return (Class<?>) typeArg
}
}
}
}
} catch (NoSuchFieldException e) {
// ignore
}
} catch (NoSuchFieldException e) {
logger.debug("[GoSDK] No 'inventories' field in " + responseClass?.simpleName)
} catch (Exception e) {
logger.warn("[GoSDK] Error finding inventory class for " + clzName + ": " + e.message)
}
// Fallback: try to find in known inventories by name
if (resourceName != null && !resourceName.isEmpty() && knownInventoryClasses != null) {
String expectedInventoryName = resourceName + "Inventory"
for (Class<?> inv : knownInventoryClasses) {
if (inv.simpleName == expectedInventoryName) {
logger.warn("[GoSDK] Found inventory by name matching for " + clzName + ": " + inv.simpleName)
return inv
}
}
}
logger.debug("[GoSDK] Could not find inventory class for API: " + clzName)
return null
}
private void parseActionAndResource() {
def actionPrefixes = ["Create", "Query", "Get", "Update", "Delete", "Destroy",
"Start", "Stop", "Reboot", "Attach", "Detach", "Change",
"Expunge", "Recover", "Migrate", "Clone", "Resize", "Add", "Remove",
"Allocate", "Apply", "Release", "Deallocate", "Validate", "Sync", "Reconnect",
"Set", "Reset", "Search", "Calculate", "Check", "Refresh",
"Batch", "Login", "Logout", "Register", "Unregister", "Security", "Ack", "Clean", "Bootstrap", "Inspect"]
for (String prefix : actionPrefixes) {
if (clzName.startsWith(prefix)) {
actionType = prefix
resourceName = clzName.substring(prefix.length())
// Further clean resourceName
resourceName = resourceName.replaceAll('Action$', '').replaceAll('Msg$', '')
return
}
}
// Extended prefixes for better grouping
def extendedPrefixes = ["SNS", "Sns", "Resume", "Migrate", "Locate", "Generate", "Export", "SelfTest",
"Calculate", "Check", "Refresh", "Sync", "Reconnect", "Archive", "Backup", "Revert"]
for (String prefix : extendedPrefixes) {
if (clzName.startsWith(prefix)) {
actionType = prefix
resourceName = clzName.substring(prefix.length())
resourceName = resourceName.replaceAll('Action$', '').replaceAll('Msg$', '')
return
}
}
actionType = ""
resourceName = clzName.replaceAll('Action$', '').replaceAll('Msg$', '')
}
private String toSnakeCase(String name) {
if (name == null || name.isEmpty()) {
return "unknown"
}
return name.replaceAll('([a-z])([A-Z])', '$1_$2').toLowerCase()
}
private String getApiPath() {
if (path.startsWith("/")) {
return "v1" + path
}
return "v1/" + path
}
List<SdkFile> generate() {
return []
}
/**
* Generate code for the response view struct (Event or Reply).
*/
String generateResponseViewCode() {
if (responseClass == null) return ""
String viewStructName = inventoryGenerator.getViewStructName(responseClass)
return inventoryGenerator.generateViewStruct(responseClass, viewStructName)
}
private String generateMethodImplementation(String apiPath, String httpMethod, String viewStructName, boolean isQueryMessage, Set<String> skipNames) {
def builder = new StringBuilder()
boolean skipMain = skipNames?.contains(clzName)
builder.append("// ${clzName} ${getMethodDescription()}\n")
// http_client unwraps inventory fields for POST/PUT requests
// Therefore Create/Add/Update/Change calls can return the Inventory View directly
// Only GET calls may need manual unwrapping
boolean unwrapForGet = !isQueryMessage &&
queryInventoryClass != null &&
viewStructName == inventoryGenerator.getViewStructName(queryInventoryClass) &&
responseClass != queryInventoryClass &&
inventoryFieldName != null &&
(actionType == "Get" || httpMethod == "GET")
String responseStructName = inventoryGenerator.getViewStructName(responseClass)
String goInventoryFieldName = inventoryFieldName != null ? inventoryFieldName.substring(0, 1).toUpperCase() + inventoryFieldName.substring(1) : "Inventory"
if (isQueryMessage) {
// Query APIs generate a list method
if (!skipMain) {
builder.append(generateQueryMethod(apiPath, viewStructName))
}
// Always generate Get(single) for Query APIs to avoid compile gaps
String getMethodName = clzName.replaceFirst('^Query', 'Get')
// Emit unless explicitly skipped (no clzName equality check)
if (!skipNames.contains(getMethodName)) {
builder.append(generateGetMethodForQuery(apiPath, viewStructName))
}
// Generate Page pagination helper for Query APIs
String pageMethodName = clzName.replaceFirst('^Query', 'Page')
if (!skipNames.contains(pageMethodName)) {
builder.append(generatePageMethod(apiPath, viewStructName))
}
} else {
if (!skipMain) {
// CRITICAL: Prioritize @RestRequest.method over actionType derived from class name
// This fixes issues like APIGetVersionMsg (actionType="Get") with method=PUT
// First check HTTP method from annotation, then fall back to actionType-based logic
if (httpMethod == "POST") {
// POST operations: Delete-via-POST needs special handling
if (actionType == "Delete") {
builder.append(generateDeleteViaPostMethod(apiPath, responseStructName))
} else {
builder.append(generateCreateMethod(apiPath, viewStructName, false, responseStructName, goInventoryFieldName))
}
} else if (httpMethod == "GET") {
// GET operations (Get/Query)
builder.append(generateGetMethod(apiPath, viewStructName, unwrapForGet, responseStructName, goInventoryFieldName))
} else if (httpMethod == "PUT") {
// PUT operations (Update/Change/Action)
// Special case: Expunge actions return void
if (actionType == "Expunge") {
builder.append(generateExpungeMethod(apiPath))
} else {
builder.append(generateUpdateMethod(apiPath, viewStructName, false, responseStructName, goInventoryFieldName))
}
} else if (httpMethod == "DELETE") {
// DELETE operations
builder.append(generateDeleteMethod(apiPath))
} else {
// Fallback for unknown HTTP methods (should rarely happen)
logger.warn("[GoSDK] Unknown HTTP method ${httpMethod} for ${clzName}, using generic method")
boolean unwrapGeneric = (httpMethod == "GET") ? unwrapForGet : false
builder.append(generateGenericMethod(apiPath, httpMethod, viewStructName, unwrapGeneric, responseStructName, goInventoryFieldName))
}
}
String asyncMethodName = "${clzName}Async"
if (supportsAsync() && shouldGenerateAsync() && !skipNames.contains(asyncMethodName)) {
builder.append(generateAsyncMethod(apiPath, httpMethod, viewStructName))
}
}
return builder.toString()
}
/**
* Public method to generate just the method implementation code.
* Used by GoInventory to consolidate "Other" actions.
*/
String generateMethodCode() {
return generateMethodCode(Collections.emptySet())
}
/**
* Generate client method code while skipping provided method names.
*/
String generateMethodCode(Set<String> skipNames) {
String apiPath = getApiPath()
String httpMethod = at.method().toString()
boolean isQuery = isQueryMessage()
Class<?> targetViewClass = queryInventoryClass != null ? queryInventoryClass : responseClass
String viewStructName = inventoryGenerator.getViewStructName(targetViewClass)
return generateMethodImplementation(apiPath, httpMethod, viewStructName, isQuery, skipNames ?: Collections.emptySet())
}
private String getMethodDescription() {
switch (actionType) {
case "Create": return "creates ${resourceName}"
case "Query": return "queries ${resourceName} list"
case "Get": return "gets ${resourceName} by uuid"
case "Update": return "updates ${resourceName}"
case "Delete": return "deletes ${resourceName}"
case "Destroy": return "destroys ${resourceName}"
case "Start": return "starts ${resourceName}"
case "Stop": return "stops ${resourceName}"
case "Change": return "changes ${resourceName}"
case "Add": return "adds ${resourceName}"
case "Remove": return "removes ${resourceName}"
default: return "operates on ${resourceName}"
}
}
private String generateCreateMethod(String apiPath, String viewStructName, boolean unwrap, String responseStructName, String fieldName) {
boolean hasParams = hasApiParams()
if (!hasParams) {
// No params: don't require user to pass params, use empty map internally
if (unwrap) {
return """func (cli *ZSClient) ${clzName}() (*view.${viewStructName}, error) {
\tvar resp view.${responseStructName}
\tif err := cli.Post("${apiPath}", map[string]interface{}{}, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp.${fieldName}, nil
}
"""
} else {
return """func (cli *ZSClient) ${clzName}() (*view.${viewStructName}, error) {
\tresp := view.${viewStructName}{}
\tif err := cli.Post("${apiPath}", map[string]interface{}{}, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
}
}
// Has params: require user to pass params
if (unwrap) {
return """func (cli *ZSClient) ${clzName}(params param.${clzName}Param) (*view.${viewStructName}, error) {
\tvar resp view.${responseStructName}
\tif err := cli.Post("${apiPath}", params, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp.${fieldName}, nil
}
"""
} else {
return """func (cli *ZSClient) ${clzName}(params param.${clzName}Param) (*view.${viewStructName}, error) {
\tresp := view.${viewStructName}{}
\tif err := cli.Post("${apiPath}", params, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
}
}
private String generateQueryMethod(String apiPath, String viewStructName) {
return """func (cli *ZSClient) ${clzName}(params *param.QueryParam) ([]view.${viewStructName}, error) {
\tvar resp []view.${viewStructName}
\treturn resp, cli.List("${apiPath}", params, &resp)
}
"""
}
/**
* Generate Page pagination method for Query APIs.
* Derive PageXxx from the QueryXxx resource name.
*/
private String generatePageMethod(String apiPath, String viewStructName) {
String pageMethodName = clzName.replaceFirst('^Query', 'Page')
String varName = resourceName.substring(0, 1).toLowerCase() + resourceName.substring(1)
if (varName.endsWith("y")) {
varName = varName.substring(0, varName.length() - 1) + "ies"
} else if (!varName.endsWith("s")) {
varName = varName + "s"
}
return """
// ${pageMethodName} Pagination
func (cli *ZSClient) ${pageMethodName}(params *param.QueryParam) ([]view.${viewStructName}, int, error) {
\tvar ${varName} []view.${viewStructName}
\ttotal, err := cli.Page("${apiPath}", params, &${varName})
\treturn ${varName}, total, err
}
"""
}
/**
* Generate Get(uuid) single-resource method for Query APIs.
* Extract the resource portion from Query{Resource}.
*/
private String generateGetMethodForQuery(String apiPath, String viewStructName) {
// Extract {Resource} from Query{Resource}
String getMethodName = clzName.replaceFirst("^Query", "Get")
// Extract URL placeholders to see if special handling is required
def placeholders = extractUrlPlaceholders(apiPath)
String cleanPath = removePlaceholders(apiPath)
// If the path has multiple placeholders (for example {category}/{name}), use GetWithSpec
if (placeholders.size() >= 2) {
String params = placeholders.collect { "${toSafeGoParamName(it)} string" }.join(", ")
String firstParam = toSafeGoParamName(placeholders[0])
def remainingPlaceholders = placeholders.drop(1)
String spec = buildSpecPath(remainingPlaceholders)
return """
func (cli *ZSClient) ${getMethodName}(${params}) (*view.${viewStructName}, error) {
\tvar resp view.${viewStructName}
\terr := cli.GetWithSpec("${cleanPath}", ${firstParam}, ${spec}, "", nil, &resp)
\tif err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
}
// Standard case: single uuid parameter
return """
func (cli *ZSClient) ${getMethodName}(uuid string) (*view.${viewStructName}, error) {
\tvar resp view.${viewStructName}
\tif err := cli.Get("${cleanPath}", uuid, nil, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
}
private String generateGetMethod(String apiPath, String viewStructName, boolean unwrap, String responseStructName, String fieldName) {
// Extract URL placeholders
def placeholders = extractUrlPlaceholders(apiPath)
String cleanPath = removePlaceholders(apiPath)
// Only use GetWithSpec when there are two or more placeholders
boolean useSpec = placeholders.size() >= 2
if (unwrap) {
if (!useSpec) {
// Check if there are any placeholders
if (placeholders.size() == 0) {
// No placeholder: no uuid parameter needed
// Use GetWithRespKey to extract the inventory field
return """func (cli *ZSClient) ${clzName}() (*view.${viewStructName}, error) {
\tvar resp view.${responseStructName}
\tif err := cli.GetWithRespKey("${cleanPath}", "", "inventory", nil, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp.${fieldName}, nil
}
"""
} else {
// Single placeholder: use GetWithRespKey with uuid to extract inventory
return """func (cli *ZSClient) ${clzName}(uuid string) (*view.${viewStructName}, error) {
\tvar resp view.${responseStructName}
\tif err := cli.GetWithRespKey("${cleanPath}", uuid, "inventory", nil, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp.${fieldName}, nil
}
"""
}
} else {
// Multiple placeholders: use GetWithSpec
// First placeholder is the resourceId; the rest form the spec
String firstParam = toSafeGoParamName(placeholders[0])
def remainingPlaceholders = placeholders.drop(1)
String params = placeholders.collect { "${toSafeGoParamName(it)} string" }.join(", ")
String spec = buildSpecPath(remainingPlaceholders)
return """func (cli *ZSClient) ${clzName}(${params}) (*view.${viewStructName}, error) {
\tvar resp view.${responseStructName}
\terr := cli.GetWithSpec("${cleanPath}", ${firstParam}, ${spec}, "", nil, &resp)
\tif err != nil {
\t\treturn nil, err
\t}
\treturn &resp.${fieldName}, nil
}
"""
}
} else {
// Not unwrapping: use responseStructName when it differs from viewStructName
// This handles cases like GetSSOClient where response is {"inventories": [...]}
// and the response wrapper (GetSSOClientView) must be used instead of the element type (SSOClientInventoryView)
String actualViewStruct = (viewStructName != responseStructName) ? responseStructName : viewStructName
if (!useSpec) {
// Check if there are any placeholders
if (placeholders.size() == 0) {
// No placeholder: no uuid parameter needed
// Use GetWithRespKey with empty responseKey to parse whole response
return """func (cli *ZSClient) ${clzName}() (*view.${actualViewStruct}, error) {
\tvar resp view.${actualViewStruct}
\tif err := cli.GetWithRespKey("${cleanPath}", "", "", nil, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
} else {
// Single placeholder: use GetWithRespKey with uuid
return """func (cli *ZSClient) ${clzName}(uuid string) (*view.${actualViewStruct}, error) {
\tvar resp view.${actualViewStruct}
\tif err := cli.GetWithRespKey("${cleanPath}", uuid, "", nil, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
}
} else {
// Multiple placeholders: use GetWithSpec
// First placeholder is the resourceId; the rest form the spec
String firstParam = toSafeGoParamName(placeholders[0])
def remainingPlaceholders = placeholders.drop(1)
String params = placeholders.collect { "${toSafeGoParamName(it)} string" }.join(", ")
String spec = buildSpecPath(remainingPlaceholders)
return """func (cli *ZSClient) ${clzName}(${params}) (*view.${actualViewStruct}, error) {
\tvar resp view.${actualViewStruct}
\terr := cli.GetWithSpec("${cleanPath}", ${firstParam}, ${spec}, "", nil, &resp)
\tif err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
}
}
}
private String generateUpdateMethod(String apiPath, String viewStructName, boolean unwrap, String responseStructName, String fieldName) {
// Extract URL placeholders
def placeholders = extractUrlPlaceholders(apiPath)
String cleanPath = removePlaceholders(apiPath)
// Determine whether this is an Action API (isAction=true or path ends with /actions)
boolean isActionApi = at.isAction() || apiPath.endsWith("/actions")
// Only use PutWithSpec when there are two or more placeholders
boolean useSpec = placeholders.size() >= 2
// Check if API has parameters
boolean hasParams = hasApiParams()
// Resolve the action key (map key for Action APIs)
// Prefer @RestRequest.parameterName, otherwise derive from class name
String actionKey
if (isActionApi) {
if (at.parameterName() != null && !at.parameterName().isEmpty() && !at.parameterName().equals("null")) {
actionKey = at.parameterName()
} else {
def apiClassName = apiMsgClazz.simpleName
def actionName = apiClassName.replaceAll('^API', '').replaceAll('Msg$', '')
actionKey = actionName.substring(0, 1).toLowerCase() + actionName.substring(1)
}
}
if (unwrap) {
if (!useSpec) {
if (placeholders.size() == 1) {
// Single placeholder pulled from the path parameter
String paramName = toSafeGoParamName(placeholders[0])
if (isActionApi) {
// Action APIs wrap params.Params inside a map
return """func (cli *ZSClient) ${clzName}(${paramName} string, params param.${clzName}Param) (*view.${viewStructName}, error) {
\tvar resp view.${responseStructName}
\tif err := cli.Put("${cleanPath}", ${paramName}, map[string]interface{}{
\t\t"${actionKey}": params.Params,
\t}, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp.${fieldName}, nil
}
"""
} else {
return """func (cli *ZSClient) ${clzName}(${paramName} string, params param.${clzName}Param) (*view.${viewStructName}, error) {
\tvar resp view.${responseStructName}
\tif err := cli.Put("${cleanPath}", ${paramName}, params, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp.${fieldName}, nil
}
"""
}
} else {
// No placeholder: use the standard Put method
if (!hasParams) {
// No params: don't require user input
if (isActionApi) {
return """func (cli *ZSClient) ${clzName}() (*view.${viewStructName}, error) {
\tvar resp view.${responseStructName}
\tif err := cli.Put("${cleanPath}", "", map[string]interface{}{
\t\t"${actionKey}": map[string]interface{}{},
\t}, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp.${fieldName}, nil
}
"""
} else {
return """func (cli *ZSClient) ${clzName}() (*view.${viewStructName}, error) {
\tvar resp view.${responseStructName}
\tif err := cli.Put("${cleanPath}", "", map[string]interface{}{}, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp.${fieldName}, nil
}
"""
}
} else if (isActionApi) {
return """func (cli *ZSClient) ${clzName}(params param.${clzName}Param) (*view.${viewStructName}, error) {
\tvar resp view.${responseStructName}
\tif err := cli.Put("${cleanPath}", "", map[string]interface{}{
\t\t"${actionKey}": params.Params,
\t}, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp.${fieldName}, nil
}
"""
} else {
return """func (cli *ZSClient) ${clzName}(uuid string, params param.${clzName}Param) (*view.${viewStructName}, error) {
\tvar resp view.${responseStructName}
\tif err := cli.Put("${cleanPath}", uuid, params, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp.${fieldName}, nil
}
"""
}
}
} else {
// Multiple placeholders: use PutWithSpec
// First placeholder is the resourceId; the rest form the spec
String firstParam = toSafeGoParamName(placeholders[0])
def remainingPlaceholders = placeholders.drop(1)
String params = placeholders.collect { "${toSafeGoParamName(it)} string" }.join(", ")
String spec = buildSpecPath(remainingPlaceholders)
return """func (cli *ZSClient) ${clzName}(${params}, params param.${clzName}Param) (*view.${viewStructName}, error) {
\tvar resp view.${responseStructName}
\terr := cli.PutWithSpec("${cleanPath}", ${firstParam}, ${spec}, "", params, &resp)
\tif err != nil {
\t\treturn nil, err
\t}
\treturn &resp.${fieldName}, nil
}
"""
}
} else {
// Variables already declared at method level, no need to redeclare
if (!useSpec) {
if (placeholders.size() == 1) {
// Single placeholder pulled from the path parameter
String paramName = toSafeGoParamName(placeholders[0])
if (isActionApi) {
// Action APIs wrap params.Params inside a map
return """func (cli *ZSClient) ${clzName}(${paramName} string, params param.${clzName}Param) (*view.${viewStructName}, error) {
\tresp := view.${viewStructName}{}
\tif err := cli.PutWithRespKey("${cleanPath}", ${paramName}, "", map[string]interface{}{
\t\t"${actionKey}": params.Params,
\t}, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
} else {
return """func (cli *ZSClient) ${clzName}(${paramName} string, params param.${clzName}Param) (*view.${viewStructName}, error) {
\tresp := view.${viewStructName}{}
\tif err := cli.PutWithRespKey("${cleanPath}", ${paramName}, "", params, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
}
} else {
// No placeholder: use the standard Put method
if (!hasParams) {
// No params: don't require user input
if (isActionApi) {
return """func (cli *ZSClient) ${clzName}() (*view.${viewStructName}, error) {
\tresp := view.${viewStructName}{}
\tif err := cli.PutWithRespKey("${cleanPath}", "", "", map[string]interface{}{
\t\t"${actionKey}": map[string]interface{}{},
\t}, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
} else {
return """func (cli *ZSClient) ${clzName}() (*view.${viewStructName}, error) {
\tresp := view.${viewStructName}{}
\tif err := cli.PutWithRespKey("${cleanPath}", "", "", map[string]interface{}{}, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
}
} else if (isActionApi) {
return """func (cli *ZSClient) ${clzName}(params param.${clzName}Param) (*view.${viewStructName}, error) {
\tresp := view.${viewStructName}{}
\tif err := cli.PutWithRespKey("${cleanPath}", "", "", map[string]interface{}{
\t\t"${actionKey}": params.Params,
\t}, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
} else {
return """func (cli *ZSClient) ${clzName}(uuid string, params param.${clzName}Param) (*view.${viewStructName}, error) {
\tresp := view.${viewStructName}{}
\tif err := cli.PutWithRespKey("${cleanPath}", uuid, "", params, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
}
}
} else {
// Multiple placeholders: use PutWithSpec
// First placeholder is the resourceId; the rest form the spec
String firstParam = toSafeGoParamName(placeholders[0])
def remainingPlaceholders = placeholders.drop(1)
String params = placeholders.collect { "${toSafeGoParamName(it)} string" }.join(", ")
String spec = buildSpecPath(remainingPlaceholders)
return """func (cli *ZSClient) ${clzName}(${params}, params param.${clzName}Param) (*view.${viewStructName}, error) {
\tresp := view.${viewStructName}{}
\terr := cli.PutWithSpec("${cleanPath}", ${firstParam}, ${spec}, "", params, &resp)
\tif err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
}
}
}
/**
* Generate Delete-via-POST method.
* Some Delete APIs use POST instead of DELETE (e.g. APIDeleteSSOClientMsg).
* These return an Event with {"success": true} and no "inventory" key,
* so we must use PostWithRespKey with empty responseKey to avoid "key not found".
*
* Handles URL placeholders (e.g. /cdp-task/{uuid}/data) by extracting them
* as function parameters and building the full path with fmt.Sprintf.
*/
private String generateDeleteViaPostMethod(String apiPath, String responseStructName) {
boolean hasParams = hasApiParams()
def placeholders = extractUrlPlaceholders(apiPath)
String cleanPath = removePlaceholders(apiPath)
if (placeholders.size() >= 1) {
// Path has URL placeholders (e.g. /cdp-task/{uuid}/data)
// Build full URL with fmt.Sprintf and add placeholders as function parameters
String fullPath = buildFullPath(placeholders)
String placeholderParams = placeholders.collect { "${toSafeGoParamName(it)} string" }.join(", ")
if (!hasParams) {
return """func (cli *ZSClient) ${clzName}(${placeholderParams}) (*view.${responseStructName}, error) {
\tresp := view.${responseStructName}{}
\tif err := cli.PostWithRespKey(${fullPath}, "", map[string]interface{}{}, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
}
return """func (cli *ZSClient) ${clzName}(${placeholderParams}, params param.${clzName}Param) (*view.${responseStructName}, error) {
\tresp := view.${responseStructName}{}
\tif err := cli.PostWithRespKey(${fullPath}, "", params, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
}
// No placeholders (e.g. /delete/sso/client)
if (!hasParams) {
return """func (cli *ZSClient) ${clzName}() (*view.${responseStructName}, error) {
\tresp := view.${responseStructName}{}
\tif err := cli.PostWithRespKey("${cleanPath}", "", map[string]interface{}{}, &resp); err != nil {
\t\treturn nil, err
\t}
\treturn &resp, nil
}
"""
}