GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — APIJSONAuto/apijson/CodeUtil.js at master · coder-caicai/APIJSONAuto

Expand file tree

/

CodeUtil.js

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
1128 lines (916 loc) · 37.9 KB
/

CodeUtil.js

Copy path

File metadata and controls

1128 lines (916 loc) · 37.9 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*Copyright ©2017 TommyLemon(https://github.com/TommyLemon/APIJSONAuto)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use CodeUtil file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/
/**util for generate code
* @author Lemon
*/
var CodeUtil = {
TAG: 'CodeUtil',
/**生成JSON的注释
* @param reqStr //已格式化的JSON String
* @param tableList
* @return parseComment
*/
parseComment: function (reqStr, tableList, method) { //怎么都获取不到真正的长度,cols不行,默认20不变,maxLineLength不行,默认undefined不变 , maxLineLength) {
if (StringUtil.isEmpty(reqStr)) {
return '';
}
method = method == null ? 'GET' : method.toUpperCase();
var lines = reqStr.split('\n');
var line;
var depth = 0;
var names = [];
var index;
var key;
var value;
var comment;
for (var i = 0; i < lines.length; i ++) {
line = lines[i].trim();
//每一种都要提取:左边的key
index = line == null ? -1 : line.indexOf(': '); //可能是 ' 或 ",所以不好用 ': , ": 判断
key = index < 0 ? '' : line.substring(1, index - 1);
if (line.endsWith(',')) {
line = line.substring(0, line.length - 1);
}
line = line.trim();
if (line.endsWith('{')) { //对象,判断是不是Table,再加对应的注释
depth ++;
names[depth] = key;
comment = CodeUtil.getComment4Request(tableList, null, key, null, method);
}
else {
if (line.endsWith('}')) {
if (line.endsWith('{}')) { //对象,判断是不是Table,再加对应的注释
comment = CodeUtil.getComment4Request(tableList, null, key, null, method);
}
else {
depth --;
continue;
}
}
else if (key == '') { //[ 1, \n 2, \n 3] 跳过
continue;
}
else { //其它,直接在后面加上注释
var isArray = line.endsWith('['); // [] 不影响
// alert('depth = ' + depth + '; line = ' + line + '; isArray = ' + isArray);
comment = value == 'null' ? ' ! null无效' : CodeUtil.getComment4Request(tableList, names[depth], key
, isArray ? '' : line.substring(index + 2).trim(), method);
}
}
lines[i] += comment;
}
return lines.join('\n');
},
/**解析出 生成iOS-Swift请求JSON 的代码
* 只需要把所有 对象标识{} 改为数组标识 []
* @param name
* @param reqObj
* @param depth
* @return parseCode
*/
parseSwift: function(name, reqObj, depth) {
name = name || '';
if (depth == null || depth < 0) {
depth = 0;
}
var hasContent = false;
return CodeUtil.parseCode(name, reqObj, {
onParseParentStart: function () {
return '[\n';
},
onParseParentEnd: function () {
return (hasContent ? '\n' : CodeUtil.getBlank(depth + 1) + ':\n') + CodeUtil.getBlank(depth) + ']';
},
onParseChildArray: function (key, value, index) {
hasContent = true;
return (index > 0 ? ',\n' : '') + CodeUtil.getBlank(depth + 1) + '"' + key + '": ' + CodeUtil.parseSwift(key, value, depth + 1);
},
onParseChildObject: function (key, value, index) {
hasContent = true;
return (index > 0 ? ',\n' : '') + CodeUtil.getBlank(depth + 1) + '"' + key + '": ' + CodeUtil.parseSwift(key, value, depth + 1);
},
onParseChildOther: function (key, value, index) {
hasContent = true;
var v; //避免改变原来的value
if (typeof value == 'string') {
log(CodeUtil.TAG, 'parseJava for typeof value === "string" >> ' );
v = '"' + value + '"';
}
else if (value instanceof Array) {
log(CodeUtil.TAG, 'parseJava for typeof value === "array" >> ' );
v = '[' + CodeUtil.getArrayString(value, '...' + name + '/' + key) + ']';
}
else {
v = value
}
return (index > 0 ? ',\n' : '') + CodeUtil.getBlank(depth + 1) + '"' + key + '": ' + v;
}
})
},
/**解析出 生成Android-Java请求JSON 的代码
* @param name
* @param reqObj
* @param depth
* @return parseCode
* @return isSmart 是否智能
*/
parseJava: function(name, reqObj, depth, isSmart) {
name = name || '';
if (depth == null || depth < 0) {
depth = 0;
}
const parentKey = JSONObject.isArrayKey(name) ? JSONResponse.getSimpleName(CodeUtil.getItemKey(name)) : CodeUtil.getTableKey(JSONResponse.getSimpleName(name));
return CodeUtil.parseCode(name, reqObj, {
onParseParentStart: function () {
return '\n' + (isSmart ? 'JSONRequest' : 'Map<String, Object>') + ' ' + parentKey + ' = new ' + (isSmart ? 'JSONRequest' : 'LinkedHashMap<>') + '();';
},
onParseParentEnd: function () {
return '';
},
onParseChildArray: function (key, value, index) {
var s = '\n\n//' + key + '<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<';
const count = isSmart ? (value.count || 0) : 0;
const page = isSmart ? (value.page || 0) : 0;
const query = isSmart ? value.query : null;
const join = isSmart ? value.join : null;
log(CodeUtil.TAG, 'parseJava for count = ' + count + '; page = ' + page);
if (isSmart) {
delete value.count;
delete value.page;
delete value.query;
delete value.join;
}
s += CodeUtil.parseJava(key, value, depth + 1, isSmart);
log(CodeUtil.TAG, 'parseJava for delete >> count = ' + count + '; page = ' + page);
var name = JSONResponse.getSimpleName(CodeUtil.getItemKey(key));
if (isSmart) {
var prefix = key.substring(0, key.length - 2);
s += '\n\n';
if (query != null) {
s += name + '.setQuery(' + (CodeUtil.QUERY_TYPE_CONSTS[query] || CodeUtil.QUERY_TYPE_CONSTS[0]) + ');\n';
}
if (StringUtil.isEmpty(join, true) == false) {
s += name + '.setJoin("' + join + '");\n';
}
s += parentKey + '.putAll(' + name + '.toArray('
+ count + ', ' + page + (prefix.length <= 0 ? '' : ', "' + prefix + '"') + '));';
}
else {
s += '\n\n' + parentKey + '.put("' + key + '", ' + name + ');';
}
s += '\n//' + key + '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n';
return s;
},
onParseChildObject: function (key, value, index) {
var s = '\n\n//' + key + '<<<<<<<<<<<<<<<<<<<<<<<<<<<<<';
const isTable = isSmart && JSONObject.isTableKey(JSONResponse.getTableName(key));
const column = isTable ? value['@column'] : null;
const group = isTable ? value['@group'] : null;
const having = isTable ? value['@having'] : null;
const order = isTable ? value['@order'] : null;
const combine = isTable ? value['@combine'] : null;
const schema = isTable ? value['@schema'] : null;
const database = isTable ? value['@database'] : null;
const role = isTable ? value['@role'] : null;
if (isTable) {
delete value['@column'];
delete value['@group'];
delete value['@having'];
delete value['@order'];
delete value['@combine'];
delete value['@schema'];
delete value['@database'];
delete value['@role'];
}
s += CodeUtil.parseJava(key, value, depth + 1, isTable);
const name = CodeUtil.getTableKey(JSONResponse.getSimpleName(key));
if (isTable) {
s = column == null ? s : s + '\n' + name + '.setColumn(' + CodeUtil.getJavaValue(name, key, column) + ');';
s = group == null ? s : s + '\n' + name + '.setGroup(' + CodeUtil.getJavaValue(name, key, group) + ');';
s = having == null ? s : s + '\n' + name + '.setHaving(' + CodeUtil.getJavaValue(name, key, having) + ');';
s = order == null ? s : s + '\n' + name + '.setOrder(' + CodeUtil.getJavaValue(name, key, order) + ');';
s = combine == null ? s : s + '\n' + name + '.setCombine(' + CodeUtil.getJavaValue(name, key, combine) + ');';
s = schema == null ? s : s + '\n' + name + '.setSchema(' + CodeUtil.getJavaValue(name, key, schema) + ');';
s = database == null ? s : s + '\n' + name + '.setDatabase(' + CodeUtil.getJavaValue(name, key, database) + ');';
s = role == null ? s : s + '\n' + name + '.setRole(' + CodeUtil.getJavaValue(name, key, role) + ');';
}
s += '\n\n' + parentKey + '.put("' + key + '", ' + name + ');';
s += '\n//' + key + '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n';
return s;
},
onParseChildOther: function (key, value, index) {
if (depth <= 0 && isSmart) {
if (key == 'tag') {
return '\n' + parentKey + '.setTag(' + CodeUtil.getJavaValue(name, key, value) + ');';
}
if (key == 'version') {
return '\n' + parentKey + '.setVersion(' + CodeUtil.getJavaValue(name, key, value) + ');';
}
if (key == 'format') {
return '\n' + parentKey + '.setFormat(' + CodeUtil.getJavaValue(name, key, value) + ');';
}
if (key == '@schema') {
return '\n' + parentKey + '.setSchema(' + CodeUtil.getJavaValue(name, key, value) + ');';
}
if (key == '@database') {
return '\n' + parentKey + '.setDatabase(' + CodeUtil.getJavaValue(name, key, value) + ');';
}
if (key == '@role') {
return '\n' + parentKey + '.setRole(' + CodeUtil.getJavaValue(name, key, value) + ');';
}
}
return '\n' + parentKey + '.put("' + key + '", ' + CodeUtil.getJavaValue(name, key, value) + ');';
}
})
},
/**TODO 为for循环生成函数
* 解析出 生成Android-Java返回结果JSON 的代码
* @param name
* @param resObj
* @param depth
* @return parseCode
*/
parseJavaResponse: function(name, resObj, depth) {
if (depth == null || depth < 0) {
depth = 0;
}
if (name == null || name == '') {
name = 'response';
}
return CodeUtil.parseCode(name, resObj, {
onParseParentStart: function () {
return depth > 0 ? '' : CodeUtil.getBlank(depth) + 'JSONResponse ' + name + ' = new JSONResponse(resultJson); \n';
},
onParseParentEnd: function () {
return '';
},
onParseChildArray: function (key, value, index) {
return this.onParseChildObject(key, value, index);
},
onParseChildObject: function (key, value, index) {
return this.onParseJSONObject(key, value, index);
},
onParseChildOther: function (key, value, index) {
if (value instanceof Array) {
log(CodeUtil.TAG, 'parseJavaResponse for typeof value === "array" >> ' );
return this.onParseJSONArray(key, value, index);
}
if (value instanceof Object) {
log(CodeUtil.TAG, 'parseJavaResponse for typeof value === "array" >> ' );
return this.onParseJSONObject(key, value, index);
}
var type = CodeUtil.getJavaTypeFromJS(key, value, true);
return '\n' + CodeUtil.getBlank(depth) + type + ' ' + key + ' = ' + name + '.get'
+ (/[A-Z]/.test(type.substring(0, 1)) ? type : StringUtil.firstCase(type + 'Value', true)) + '("' + key + '");';
},
onParseJSONArray: function (key, value, index) {
var padding = '\n' + CodeUtil.getBlank(depth);
var innerPadding = padding + CodeUtil.getBlank(1);
var k = JSONResponse.replaceArray(key);
//还有其它字段冲突以及for循环的i冲突,解决不完的,只能让开发者自己抽出函数 var item = StringUtil.addSuffix(k, 'Item');
var type = CodeUtil.getJavaTypeFromJS('item', value[0], false);
var s = '\n' + padding + '//' + key + '<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<';
s += padding + 'JSONArray ' + k + ' = JSON.nullToEmpty(' + name + '.getJSONArray("' + key + '"));';
s += '\n' + padding + '//TODO 把这段代码抽取一个函数,以免for循环嵌套时 i 冲突 或 id等其它字段冲突';
s += padding + type + ' item;';
s += padding + 'for (int i = 0; i < ' + k + '.size(); i++) {';
s += innerPadding + 'item = ' + k + '.get' + type + '(i);';
s += innerPadding + 'if (item == null) {';
s += innerPadding + ' continue;';
s += innerPadding + '}';
//不能生成N个,以第0个为准,可能会不全,剩下的由开发者自己补充。 for (var i = 0; i < value.length; i ++) {
if (value[0] instanceof Object) {
s += CodeUtil.parseJavaResponse('item', value[0], depth + 1);
}
// }
s += padding + '}';
s += padding + '//' + key + '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n';
return s;
},
onParseJSONObject: function (key, value, index) {
var padding = '\n' + CodeUtil.getBlank(depth);
var k = StringUtil.firstCase(JSONResponse.getSimpleName(key));
var s = '\n' + padding + '//' + key + '<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<';
s += padding + 'JSONObject ' + k + ' = JSON.nullToEmpty(' + name + '.getJSONObject("' + key + '"));\n'
s += CodeUtil.parseJavaResponse(k, value, depth);
s += padding + '//' + key + '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n';
return s;
}
})
},
/**解析出 生成请求JSON 的代码
* @param name
* @param reqObj
* @param callback Object,带以下回调函数function:
* 解析父对象Parent的onParseParentStart和onParseParentEnd,
* 解析APIJSON数组Object的onParseArray,
* 解析普通Object的onParseObject,
* 解析其它键值对的onParseOther.
*
* 其中每个都必须返回String,空的情况下返回'' -> response += callback.fun(...)
* @return
*/
parseCode: function(name, reqObj, callback) {
if (reqObj == null || reqObj == '') {
log(CodeUtil.TAG, 'parseCode reqObj == null || reqObj.isEmpty() >> return null;');
return null;
}
if (typeof reqObj != 'object') {
log(CodeUtil.TAG, 'parseCode typeof reqObj != object >> return null;');
return null;
}
log(CodeUtil.TAG, '\n\n\n parseCode name = ' + name + '; reqObj = \n' + format(JSON.stringify(reqObj)));
var response = callback.onParseParentStart();
var index = 0; //实际有效键值对key:value的所在reqObj内的位置
var value;
for (var key in reqObj) {
log(CodeUtil.TAG, 'parseCode for key = ' + key);
//key == null || value == null 的键值对被视为无效
value = key == null ? null : reqObj[key];
if (value == null) {
continue;
}
log(CodeUtil.TAG, 'parseCode for index = ' + index);
if (value instanceof Object && (value instanceof Array) == false) {//APIJSON Array转为常规JSONArray
log(CodeUtil.TAG, 'parseCode for typeof value === "object" >> ' );
if (JSONObject.isArrayKey(key)) { // APIJSON Array转为常规JSONArray
log(CodeUtil.TAG, 'parseCode for JSONObject.isArrayKey(key) >> ' );
response += callback.onParseChildArray(key, value, index);
}
else { // 常规JSONObject,往下一级提取
log(CodeUtil.TAG, 'parseCode for JSONObject.isArrayKey(key) == false >> ' );
response += callback.onParseChildObject(key, value, index);
}
}
else { // 其它Object,直接填充
response += callback.onParseChildOther(key, value, index);
}
index ++;
}
response += callback.onParseParentEnd();
log(CodeUtil.TAG, 'parseCode return response = \n' + response + '\n\n\n');
return response;
},
/**用数据字典转为JavaBean
* @param docObj
*/
parseJavaBean: function(docObj, clazz) {
//转为Java代码格式
var doc = '';
var item;
//[] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
var list = docObj == null ? null : docObj['[]'];
if (list != null) {
console.log('parseJavaBean [] = \n' + format(JSON.stringify(list)));
var table;
var model;
var columnList;
var column;
for (var i = 0; i < list.length; i++) {
item = list[i];
//Table
table = item == null ? null : item.Table;
model = CodeUtil.getModelName(table == null ? null : table.TABLE_NAME);
if (model != clazz) {
continue;
}
console.log('parseJavaBean [] for i=' + i + ': table = \n' + format(JSON.stringify(table)));
doc += '/*'
+ '\nAPIJSONAuto自动生成JavaBean\n主页: http://apijson.cn'
+ '\n\n使用方法\n1.修改包名package \n2.import需要引入的类,可使用快捷键Ctrl+Shift+O '
+ '\n*/\n'
+ '\npackage apijson.demo.server.model;\n\n\n'
+ CodeUtil.getComment(table.TABLE_COMMENT, true)
+ '\n@MethodAccess'
+ '\npublic class ' + model + ' implements Serializable {'
+ '\n private static final long serialVersionUID = 1L;\n';
//Column[]
columnList = item['Column[]'];
if (columnList != null) {
console.log('parseJavaBean [] for ' + i + ': columnList = \n' + format(JSON.stringify(columnList)));
var name;
var type;
for (var j = 0; j < columnList.length; j++) {
column = columnList[j];
name = CodeUtil.getFieldName(column == null ? null : column.COLUMN_NAME);
if (name == '') {
continue;
}
type = name == 'id' ? 'Long' : CodeUtil.getJavaType(column.COLUMN_TYPE, false);
console.log('parseJavaBean [] for j=' + j + ': column = \n' + format(JSON.stringify(column)));
doc += '\n private ' + type + ' ' + name + '; ' + CodeUtil.getComment(column.COLUMN_COMMENT, false);
}
doc += '\n\n'
+ '\n public ' + model + '() {'
+ '\n super();'
+ '\n }'
+ '\n public ' + model + '(long id) {'
+ '\n this();'
+ '\n setId(id);'
+ '\n }'
+ '\n\n\n\n'
for (var j = 0; j < columnList.length; j++) {
column = columnList[j];
name = CodeUtil.getFieldName(column == null ? null : column.COLUMN_NAME);
if (name == '') {
continue;
}
type = name == 'id' ? 'Long' : CodeUtil.getJavaType(column.COLUMN_TYPE);
console.log('parseJavaBean [] for j=' + j + ': column = \n' + format(JSON.stringify(column)));
//getter
doc += '\n public ' + type + ' ' + CodeUtil.getMethodName('get', name) + '() {'
+ '\n return ' + name + ';\n }\n';
//setter
doc += '\n public ' + model + ' ' + CodeUtil.getMethodName('set', name) + '(' + type + ' ' + name + ') {'
+ '\n this.' + name + ' = ' + name + ';'
+ '\n return this;\n }\n';
}
}
doc += '\n\n}';
}
}
//[] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
return doc;
},
/**获取model类名
* @param tableName
* @return {*}
*/
getModelName: function(tableName) {
var model = StringUtil.noBlank(tableName);
if (model == '') {
return model;
}
var lastIndex = model.lastIndexOf('_');
if (lastIndex >= 0) {
model = model.substring(lastIndex + 1);
}
return StringUtil.firstCase(model, true);
},
/**获取model成员变量名
* @param columnName
* @return {*}
*/
getFieldName: function(columnName) {
return StringUtil.firstCase(StringUtil.noBlank(columnName), false);
},
/**获取model方法名
* @param prefix @NotNull 前缀,一般是get,set等
* @param field @NotNull
* @return {*}
*/
getMethodName: function(prefix, field) {
if (field.startsWith('_')) {
field = '_' + field; //get_name 会被fastjson解析为name而不是_name,所以要多加一个_
}
return prefix + StringUtil.firstCase(field, true);
},
/**获取注释
* @param comment
* @param multiple 多行
* @param prefix 多行注释的前缀,一般是空格
* @return {*}
*/
getComment: function(comment, multiple, prefix) {
comment = comment == null ? '' : comment.trim();
if (prefix == null) {
prefix = '';
}
if (multiple == false) {
return prefix + '//' + comment.replace(/\n/g, ' ');
}
//多行注释,需要每行加 * 和空格
var newComment = prefix + '/**';
var index;
do {
newComment += '\n';
index = comment.indexOf('\n');
if (index < 0) {
newComment += prefix + ' * ' + comment;
break;
}
newComment += prefix + ' * ' + comment.substring(0, index);
comment = comment.substring(index + 2);
}
while(comment != '')
return newComment + '\n' + prefix + ' */';
},
/**获取Java的值
* @param value
* @return {*}
*/
getJavaValue: function (name, key, value) {
var v; //避免改变原来的value
if (typeof value == 'string') {
log(CodeUtil.TAG, 'parseJava for typeof value === "string" >> ' );
v = '"' + value + '"';
}
else if (value instanceof Array) {
log(CodeUtil.TAG, 'parseJava for typeof value === "array" >> ' );
v = 'new Object[]{' + CodeUtil.getArrayString(value, '...' + name + '/' + key) + '}';
}
else {
v = value
}
return v;
},
getJavaTypeFromJS: function (key, value, baseFirst) {
if (typeof value == 'boolean') {
return baseFirst ? 'boolean' : 'Boolean';
}
if (typeof value == 'number') {
if (String(value).indexOf(".") >= 0) {
return baseFirst ? 'double' : 'Double';
}
if (Math.abs(value) >= 2147483647 || CodeUtil.isId(key)) {
return baseFirst ? 'long' : 'Long';
}
return baseFirst ? 'int' : 'Integer';
}
if (typeof value == 'string') {
return 'String';
}
if (value instanceof Array) {
return 'JSONArray';
}
if (value instanceof Object) {
return 'JSONObject';
}
return 'Object';
},
/**根据数据库类型获取Java类型
* @param t
* @param saveLength
*/
getJavaType: function(type, saveLength) {
type = StringUtil.noBlank(type);
var index = type.indexOf('(');
var t = index < 0 ? type : type.substring(0, index);
if (t == '') {
return 'Object';
}
var length = index < 0 || saveLength != true ? '' : type.substring(index);
if (t.endsWith('char') || t.endsWith('text') || t == 'enum' || t == 'set') {
return 'String' + length;
}
if (t.endsWith('int') || t == 'integer') {
return (t == 'bigint' ? 'Long' : 'Integer') + length;
}
if (t.endsWith('binary') || t.endsWith('blob')) {
return 'byte[]' + length;
}
switch (t) {
case 'id':
return 'Long' + length;
case 'bit':
return 'Boolean' + length;
case 'bool': //同tinyint
case 'boolean': //同tinyint
return 'Integer' + length;
case 'datetime':
return 'Timestamp' + length;
case 'year':
return 'Date' + length;
case 'decimal':
return 'BigDecimal' + length;
case 'json':
return 'List<String>' + length;
default:
return StringUtil.firstCase(t, true) + length;
}
},
/**获取字段对应值的最大长度
* @param columnType
* @return {string}
*/
getMaxLength: function (columnType) {
var index = columnType == null ? -1 : columnType.indexOf('(');
return index < 0 ? '不限' : columnType.substring(index + 1, columnType.length - (columnType.endsWith(')') ? 1 : 0));
},
/**根据层级获取键值对前面的空格
* @param depth
* @return {string}
*/
getBlank: function(depth) {
var s = '';
for (var i = 0; i < depth; i ++) {
s += ' ';
}
return s;
},
/**根据数组arr生成用 , 分割的字符串
* 直接用 join 会导致里面的 String 没有被 "" 包裹
* @param arr
* @param path
*/
getArrayString: function(arr, path) {
if (arr == null || arr.length <= 0) {
return arr;
}
var s = '';
var v;
var t;
for (var i = 0; i < arr.length; i ++) {
t = typeof arr[i];
if (t == 'object' || t == 'array') {
//TODO 不止为什么parseJavaResponse会调用这个函数,先放过 throw new Error('请求JSON中 ' + (path || '""') + ':[] 格式错误!key:[] 的[]中所有元素都不能为对象{}或数组[] !');
}
v = (t == 'string' ? '"' + arr[i] + '"': arr[i]) //只支持基本类型
s += (i > 0 ? ', ' : '') + v;
}
return s;
},
/**获取Table变量名
* @param key
* @return empty ? 'request' : key
*/
getTableKey: function(key) {
key = StringUtil.trim(key);
return key == '' ? 'request' : StringUtil.firstCase(key, false);//StringUtil.addSuffix(key, 'Request');
},
/**获取数组内Object变量名
* @param key
* @return empty ? 'item' : key + 'Item' 且首字母小写
*/
getItemKey: function(key) {
return StringUtil.addSuffix(key.substring(0, key.length - 2), 'Item');
},
/**是否为id
* @param column
* @return {boolean}
*/
isId: function (column) {
if (column == null) {
return false;
}
if (column.endsWith('Id')) { // lowerCamelCase
return true;
}
var index = column.lastIndexOf('_'); // snake_case
var id = index < 0 ? column : column.substring(index + 1);
return id.toLowerCase() == 'id';
},
QUERY_TYPES: ['数据', '数量', '全部'],
QUERY_TYPE_KEYS: [0, 1, 2],
QUERY_TYPE_CONSTS: ["JSONRequest.QUERY_TABLE", "JSONRequest.QUERY_TOTAL", "JSONRequest.QUERY_ALL"],
REQUEST_ROLE_KEYS: ['UNKNOWN', 'LOGIN', 'CONTACT', 'CIRCLE', 'OWNER', 'ADMIN'],
REQUEST_ROLE: {
UNKNOWN: '未登录',
LOGIN: '已登录',
CONTACT: '联系人',
CIRCLE: '圈子成员',
OWNER: '拥有者',
ADMIN: '管理员'
},
REQUEST_DATABASE_KEYS: ['MYSQL', 'POSTGRESQL', 'ORACLE'],
/**获取请求JSON的注释
* @param tableList
* @param name
* @param key
* @param value
*/
getComment4Request: function (tableList, name, key, value, method) {
// alert('name = ' + name + '; key = ' + key + '; value = ' + value + '; method = ' + method);
if (key == null) {
return '';
}
if (value == null || value instanceof Object) {
if (JSONObject.isArrayKey(key)) {
if (method != 'GET') {
return ' ! key[]:{}只支持GET方法!';
}
key = key.substring(0, key.lastIndexOf('[]'));
var aliaIndex = key.indexOf(':');
var objName = aliaIndex < 0 ? key : key.substring(0, aliaIndex);
var alias = aliaIndex < 0 ? '' : key.substring(aliaIndex + 1, key.length);
var firstIndex = objName.indexOf('-');
var firstKey = firstIndex < 0 ? objName : objName.substring(0, firstIndex);
alias = alias.length <= 0 ? '' : '新建别名: ' + alias + ' < ';
return CodeUtil.getComment((JSONObject.isTableKey(firstKey) ? '提取' + objName + ' < ' : '') + alias + '数组', false, ' ');
}
var aliaIndex = key.indexOf(':');
var objName = aliaIndex < 0 ? key : key.substring(0, aliaIndex);
if (JSONObject.isTableKey(objName)) {
var c = CodeUtil.getCommentFromDoc(tableList, objName, null, method);
return StringUtil.isEmpty(c) ? ' ! 表不存在!' : CodeUtil.getComment(
(aliaIndex < 0 ? '' : '新建别名: ' + key.substring(aliaIndex + 1, key.length) + ' < ' + objName + ': ') + c, false, ' ');
}
return '';
}
if (JSONObject.isArrayKey(name)) {
switch (key) {
case 'count':
return CodeUtil.getType4Request(value) != 'number' ? ' ! value必须是Number类型!' : CodeUtil.getComment('最多数量: 例如 5 10 20 ...', false, ' ');
case 'page':
if (CodeUtil.getType4Request(value) != 'number') {
return ' ! value必须是Number类型!';
}
return value < 0 ? ' ! 必须 >= 0 !' : CodeUtil.getComment('分页页码: 例如 0 1 2 ...', false, ' ');
case 'query':
var query = CodeUtil.QUERY_TYPES[value];
return StringUtil.isEmpty(query) ? ' ! value必须是[' + CodeUtil.QUERY_TYPE_KEYS.join() + ']中的一种!' : CodeUtil.getComment('查询内容:0-数据 1-总数 2-全部', false, ' ');
case 'join':
return CodeUtil.getType4Request(value) != 'string' ? ' ! value必须是String类型!' : CodeUtil.getComment('多表连接:例如 &/User/id@,</Comment/momentId@,...', false, ' ');
}
return '';
}
var aliaIndex = name.indexOf(':');
var objName = aliaIndex < 0 ? name : name.substring(0, aliaIndex);
if (JSONObject.isTableKey(objName)) {
switch (key) {
case '@column':
return CodeUtil.getType4Request(value) != 'string' ? ' ! value必须是String类型!' : CodeUtil.getComment('返回字段:例如 id,name;json_length(contactIdList):contactCount;...', false, ' ');
case '@group':
return CodeUtil.getType4Request(value) != 'string' ? ' ! value必须是String类型!' : CodeUtil.getComment('分组方式:例如 userId,momentId,...', false, ' ');
case '@having':
return CodeUtil.getType4Request(value) != 'string' ? ' ! value必须是String类型!' : CodeUtil.getComment('SQL函数:例如 max(id)>100;sum(balance)<=10000;...', false, ' ');
case '@order':
return CodeUtil.getType4Request(value) != 'string' ? ' ! value必须是String类型!' : CodeUtil.getComment('排序方式:+升序,-降序,例如 name+,date-,...', false, ' ');
case '@combine':
return CodeUtil.getType4Request(value) != 'string' ? ' ! value必须是String类型!' : CodeUtil.getComment('条件组合:例如 name?,|tag?,&id{},!id,...', false, ' ');
case '@schema':
return CodeUtil.getType4Request(value) != 'string' ? ' ! value必须是String类型!' : CodeUtil.getComment('集合空间:例如 sys apijson ...', false, ' ');
case '@database':
try {
value = value.substring(1, value.length - 1).toUpperCase();
} catch (e) {}
return CodeUtil.REQUEST_DATABASE_KEYS.indexOf(value) < 0 ? ' ! value必须是[' + CodeUtil.REQUEST_DATABASE_KEYS.join() + ']中的一种!' : CodeUtil.getComment('数据库:例如 MYSQL POSTGRESQL ORACLE ...', false, ' ');
case '@role':
try {
value = value.substring(1, value.length - 1).toUpperCase();
} catch (e) {}
var role = CodeUtil.REQUEST_ROLE[value];
return StringUtil.isEmpty(role) ? ' ! value必须是[' + CodeUtil.REQUEST_ROLE_KEYS.join() + ']中的一种!' : CodeUtil.getComment('来访角色:' + role, false, ' ');
}
if (key.startsWith('@')) {
return '';
}
var c = CodeUtil.getCommentFromDoc(tableList, objName, key, method);
return StringUtil.isEmpty(c) ? ' ! 字段不存在!' : CodeUtil.getComment(c, false, ' ');
}
// alert('name = ' + name + '; key = ' + key);
if (StringUtil.isEmpty(name)) {
switch (key) {
case 'tag':
if (method == 'GET' || method == 'HEAD') {
return '';
}
return CodeUtil.getType4Request(value) != 'string' ? ' ! value必须是String类型!' : CodeUtil.getComment('请求密钥:例如 User Comment[] Privacy-CIRCLE ...', false, ' ');
case 'version':
if (method == 'GET' || method == 'HEAD') {
return '';
}
return CodeUtil.getType4Request(value) != 'number' ? ' ! value必须是Number类型!' : CodeUtil.getComment('版本号: 例如 1 2 3 ...', false, ' ');
case 'format':
return CodeUtil.getType4Request(value) != 'boolean' ? ' ! value必须是Boolean类型!' : CodeUtil.getComment('格式化: true-是 false-否', false, ' ');
case '@schema':
return CodeUtil.getType4Request(value) != 'string' ? ' ! value必须是String类型!' : CodeUtil.getComment('集合空间:例如 sys apijson ...', false, ' ');
case '@database':
try {
value = value.substring(1, value.length - 1).toUpperCase();
} catch (e) {}
return CodeUtil.REQUEST_DATABASE_KEYS.indexOf(value) < 0 ? ' ! value必须是[' + CodeUtil.REQUEST_DATABASE_KEYS.join() + ']中的一种!' : CodeUtil.getComment('数据库:例如 MYSQL POSTGRESQL ORACLE ...', false, ' ');
case '@role':
try {
value = value.substring(1, value.length - 1).toUpperCase();
} catch (e) {}
var role = CodeUtil.REQUEST_ROLE[value];
return StringUtil.isEmpty(role) ? ' ! value必须是[' + CodeUtil.REQUEST_ROLE_KEYS.join() + ']中的一种!' : CodeUtil.getComment('默认角色:' + role, false, ' ');
}
}
return '';
},
/**
* @param tableList
* @param tableName
* @param columnName
* @param method
* @return {*}
*/
getCommentFromDoc: function (tableList, tableName, columnName, method) {
log('getCommentFromDoc tableName = ' + tableName + '; columnName = ' + columnName + '; method = ' + method + '; tableList = \n' + JSON.stringify(tableList));
if (tableList == null || tableList.length <= 0) {
return '...';
}
var item;
var table;
var columnList;
var column;
for (var i = 0; i < tableList.length; i++) {
item = tableList[i];
//Table
View remainder of file in raw view
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.