-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
AbstractParser.java
executable file
·1594 lines (1373 loc) · 48.6 KB
/
AbstractParser.java
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 (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
This source code is licensed under the Apache License Version 2.0.*/
package apijson.orm;
import static apijson.JSONObject.KEY_EXPLAIN;
import static apijson.RequestMethod.GET;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.TimeoutException;
import javax.activation.UnsupportedDataTypeException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import apijson.JSON;
import apijson.JSONResponse;
import apijson.Log;
import apijson.NotNull;
import apijson.RequestMethod;
import apijson.RequestRole;
import apijson.StringUtil;
import apijson.orm.exception.ConditionErrorException;
import apijson.orm.exception.ConflictException;
import apijson.orm.exception.NotExistException;
import apijson.orm.exception.NotLoggedInException;
import apijson.orm.exception.OutOfRangeException;
/**parser for parsing request to JSONObject
* @author Lemon
*/
public abstract class AbstractParser<T> implements Parser<T>, ParserCreator<T>, VerifierCreator<T>, SQLCreator {
protected static final String TAG = "AbstractParser";
/**
* method = null
*/
public AbstractParser() {
this(null);
}
/**needVerify = true
* @param requestMethod null ? requestMethod = GET
*/
public AbstractParser(RequestMethod method) {
this(method, true);
}
/**
* @param requestMethod null ? requestMethod = GET
* @param needVerify 仅限于为服务端提供方法免验证特权,普通请求不要设置为 false ! 如果对应Table有权限也建议用默认值 true,保持和客户端权限一致
*/
public AbstractParser(RequestMethod method, boolean needVerify) {
super();
setMethod(method);
setNeedVerify(needVerify);
}
@NotNull
protected Visitor<T> visitor;
@NotNull
@Override
public Visitor<T> getVisitor() {
if (visitor == null) {
visitor = new Visitor<T>() {
@Override
public T getId() {
return null;
}
@Override
public List<T> getContactIdList() {
return null;
}
};
}
return visitor;
}
@Override
public AbstractParser<T> setVisitor(@NotNull Visitor<T> visitor) {
this.visitor = visitor;
return this;
}
protected RequestMethod requestMethod;
@NotNull
@Override
public RequestMethod getMethod() {
return requestMethod;
}
@NotNull
@Override
public AbstractParser<T> setMethod(RequestMethod method) {
this.requestMethod = method == null ? GET : method;
this.transactionIsolation = RequestMethod.isQueryMethod(method) ? Connection.TRANSACTION_NONE : Connection.TRANSACTION_REPEATABLE_READ;
return this;
}
protected int version;
@Override
public int getVersion() {
return version;
}
@Override
public AbstractParser<T> setVersion(int version) {
this.version = version;
return this;
}
protected String tag;
@Override
public String getTag() {
return tag;
}
@Override
public AbstractParser<T> setTag(String tag) {
this.tag = tag;
return this;
}
protected JSONObject requestObject;
@Override
public JSONObject getRequest() {
return requestObject;
}
@Override
public AbstractParser<T> setRequest(JSONObject request) {
this.requestObject = request;
return this;
}
protected Boolean globleFormat;
public AbstractParser<T> setGlobleFormat(Boolean globleFormat) {
this.globleFormat = globleFormat;
return this;
}
@Override
public Boolean getGlobleFormat() {
return globleFormat;
}
protected RequestRole globleRole;
public AbstractParser<T> setGlobleRole(RequestRole globleRole) {
this.globleRole = globleRole;
return this;
}
@Override
public RequestRole getGlobleRole() {
return globleRole;
}
protected String globleDatabase;
public AbstractParser<T> setGlobleDatabase(String globleDatabase) {
this.globleDatabase = globleDatabase;
return this;
}
@Override
public String getGlobleDatabase() {
return globleDatabase;
}
protected String globleSchema;
public AbstractParser<T> setGlobleSchema(String globleSchema) {
this.globleSchema = globleSchema;
return this;
}
@Override
public String getGlobleSchema() {
return globleSchema;
}
protected Boolean globleExplain;
public AbstractParser<T> setGlobleExplain(Boolean globleExplain) {
this.globleExplain = globleExplain;
return this;
}
@Override
public Boolean getGlobleExplain() {
return globleExplain;
}
protected String globleCache;
public AbstractParser<T> setGlobleCache(String globleCache) {
this.globleCache = globleCache;
return this;
}
@Override
public String getGlobleCache() {
return globleCache;
}
@Override
public AbstractParser<T> setNeedVerify(boolean needVerify) {
setNeedVerifyLogin(needVerify);
setNeedVerifyRole(needVerify);
setNeedVerifyContent(needVerify);
return this;
}
protected boolean needVerifyLogin;
@Override
public boolean isNeedVerifyLogin() {
return needVerifyLogin;
}
@Override
public AbstractParser<T> setNeedVerifyLogin(boolean needVerifyLogin) {
this.needVerifyLogin = needVerifyLogin;
return this;
}
protected boolean needVerifyRole;
@Override
public boolean isNeedVerifyRole() {
return needVerifyRole;
}
@Override
public AbstractParser<T> setNeedVerifyRole(boolean needVerifyRole) {
this.needVerifyRole = needVerifyRole;
return this;
}
protected boolean needVerifyContent;
@Override
public boolean isNeedVerifyContent() {
return needVerifyContent;
}
@Override
public AbstractParser<T> setNeedVerifyContent(boolean needVerifyContent) {
this.needVerifyContent = needVerifyContent;
return this;
}
protected SQLExecutor sqlExecutor;
protected Verifier<T> verifier;
protected Map<String, Object> queryResultMap;//path-result
@Override
public SQLExecutor getSQLExecutor() {
if (sqlExecutor == null) {
sqlExecutor = createSQLExecutor();
}
return sqlExecutor;
}
@Override
public Verifier<T> getVerifier() {
if (verifier == null) {
verifier = createVerifier().setVisitor(getVisitor());
}
return verifier;
}
/**解析请求json并获取对应结果
* @param request
* @return
*/
@Override
public String parse(String request) {
return JSON.toJSONString(parseResponse(request));
}
/**解析请求json并获取对应结果
* @param request
* @return
*/
@NotNull
@Override
public String parse(JSONObject request) {
return JSON.toJSONString(parseResponse(request));
}
/**解析请求json并获取对应结果
* @param request 先parseRequest中URLDecoder.decode(request, UTF_8);再parseResponse(getCorrectRequest(...))
* @return parseResponse(requestObject);
*/
@NotNull
@Override
public JSONObject parseResponse(String request) {
Log.d(TAG, "\n\n\n\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n"
+ requestMethod + "/parseResponse request = \n" + request + "\n\n");
try {
requestObject = parseRequest(request);
} catch (Exception e) {
return newErrorResult(e);
}
return parseResponse(requestObject);
}
private int queryDepth;
/**解析请求json并获取对应结果
* @param request
* @return requestObject
*/
@NotNull
@Override
public JSONObject parseResponse(JSONObject request) {
long startTime = System.currentTimeMillis();
Log.d(TAG, "parseResponse startTime = " + startTime
+ "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n ");
requestObject = request;
verifier = createVerifier().setVisitor(getVisitor());
if (RequestMethod.isPublicMethod(requestMethod) == false) {
try {
if (isNeedVerifyLogin()) {
onVerifyLogin();
}
if (isNeedVerifyContent()) {
onVerifyContent();
}
} catch (Exception e) {
return extendErrorResult(requestObject, e);
}
}
//必须在parseCorrectRequest后面,因为parseCorrectRequest可能会添加 @role
if (isNeedVerifyRole() && globleRole == null) {
try {
setGlobleRole(RequestRole.get(requestObject.getString(JSONRequest.KEY_ROLE)));
requestObject.remove(JSONRequest.KEY_ROLE);
} catch (Exception e) {
return extendErrorResult(requestObject, e);
}
}
try {
setGlobleFormat(requestObject.getBoolean(JSONRequest.KEY_FORMAT));
setGlobleDatabase(requestObject.getString(JSONRequest.KEY_DATABASE));
setGlobleSchema(requestObject.getString(JSONRequest.KEY_SCHEMA));
setGlobleExplain(requestObject.getBoolean(JSONRequest.KEY_EXPLAIN));
setGlobleCache(requestObject.getString(JSONRequest.KEY_CACHE));
requestObject.remove(JSONRequest.KEY_FORMAT);
requestObject.remove(JSONRequest.KEY_DATABASE);
requestObject.remove(JSONRequest.KEY_SCHEMA);
requestObject.remove(JSONRequest.KEY_EXPLAIN);
requestObject.remove(JSONRequest.KEY_CACHE);
} catch (Exception e) {
return extendErrorResult(requestObject, e);
}
final String requestString = JSON.toJSONString(request);//request传进去解析后已经变了
queryResultMap = new HashMap<String, Object>();
Exception error = null;
sqlExecutor = createSQLExecutor();
onBegin();
try {
queryDepth = 0;
requestObject = onObjectParse(request, null, null, null, false);
onCommit();
}
catch (Exception e) {
e.printStackTrace();
error = e;
onRollback();
}
requestObject = error == null ? extendSuccessResult(requestObject) : extendErrorResult(requestObject, error);
JSONObject res = (globleFormat != null && globleFormat) && JSONResponse.isSuccess(requestObject) ? new JSONResponse(requestObject) : requestObject;
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
if (Log.DEBUG) { //用 | 替代 /,避免 APIJSON ORM,APIAuto 等解析路径错误
requestObject.put("sql:generate|cache|execute|maxExecute", getSQLExecutor().getGeneratedSQLCount() + "|" + getSQLExecutor().getCachedSQLCount() + "|" + getSQLExecutor().getExecutedSQLCount() + "|" + getMaxSQLCount());
requestObject.put("depth:count|max", queryDepth + "|" + getMaxQueryDepth());
requestObject.put("time:start|duration|end", startTime + "|" + duration + "|" + endTime);
if (error != null) {
requestObject.put("throw", error.getClass().getName());
requestObject.put("trace", error.getStackTrace());
}
}
onClose();
//会不会导致原来的session = null? session = null;
if (Log.DEBUG) {
Log.d(TAG, "\n\n\n\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n "
+ requestMethod + "/parseResponse request = \n" + requestString + "\n\n");
Log.d(TAG, "parseResponse return response = \n" + JSON.toJSONString(requestObject)
+ "\n >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> \n\n\n");
}
Log.d(TAG, "parseResponse endTime = " + endTime + "; duration = " + duration
+ ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\n");
return res;
}
@Override
public void onVerifyLogin() throws Exception {
getVerifier().verifyLogin();
}
@Override
public void onVerifyContent() throws Exception {
requestObject = parseCorrectRequest();
}
/**校验角色及对应操作的权限
* @param config
* @return
* @throws Exception
*/
@Override
public void onVerifyRole(@NotNull SQLConfig config) throws Exception {
if (Log.DEBUG) {
Log.i(TAG, "onVerifyRole config = " + JSON.toJSONString(config));
}
if (isNeedVerifyRole()) {
if (config.getRole() == null) {
if (globleRole != null) {
config.setRole(globleRole);
} else {
config.setRole(getVisitor().getId() == null ? RequestRole.UNKNOWN : RequestRole.LOGIN);
}
}
getVerifier().verifyAccess(config);
}
}
/**解析请求JSONObject
* @param request => URLDecoder.decode(request, UTF_8);
* @return
* @throws Exception
*/
@NotNull
public static JSONObject parseRequest(String request) throws Exception {
JSONObject obj = JSON.parseObject(request);
if (obj == null) {
throw new UnsupportedEncodingException("JSON格式不合法!");
}
return obj;
}
@Override
public JSONObject parseCorrectRequest(RequestMethod method, String tag, int version, String name, @NotNull JSONObject request
, int maxUpdateCount, SQLCreator creator) throws Exception {
if (RequestMethod.isPublicMethod(method)) {
return request;//需要指定JSON结构的get请求可以改为post请求。一般只有对安全性要求高的才会指定,而这种情况用明文的GET方式几乎肯定不安全
}
if (StringUtil.isEmpty(tag, true)) {
throw new IllegalArgumentException("请在最外层传 tag !一般是 Table 名,例如 \"tag\": \"User\" ");
}
//获取指定的JSON结构 <<<<<<<<<<<<
JSONObject object = null;
String error = "";
try {
object = getStructure("Request", method.name(), tag, version);
} catch (Exception e) {
error = e.getMessage();
}
if (object == null) { //empty表示随意操作 || object.isEmpty()) {
throw new UnsupportedOperationException("找不到 version: " + version + ", method: " + method.name() + ", tag: " + tag + " 对应的 structure !"
+ "非开放请求必须是后端 Request 表中校验规则允许的操作!\n " + error + "\n如果需要则在 Request 表中新增配置!");
}
JSONObject target = object;
if (object.containsKey(tag) == false) { //tag 是 Table 名或 Table[]
boolean isArrayKey = tag.endsWith(":[]"); // JSONRequest.isArrayKey(tag);
String key = isArrayKey ? tag.substring(0, tag.length() - 3) : tag;
if (apijson.JSONObject.isTableKey(key)) {
if (isArrayKey) { //自动为 tag = Comment:[] 的 { ... } 新增键值对 "Comment[]":[] 为 { "Comment[]":[], ... }
target.put(key + "[]", new JSONArray());
}
else { //自动为 tag = Comment 的 { ... } 包一层为 { "Comment": { ... } }
target = new JSONObject(true);
target.put(tag, object);
}
}
}
//获取指定的JSON结构 >>>>>>>>>>>>>>
//JSONObject clone 浅拷贝没用,Structure.parse 会导致 structure 里面被清空,第二次从缓存里取到的就是 {}
return getVerifier().verifyRequest(method, name, target, request, maxUpdateCount, getGlobleDatabase(), getGlobleSchema(), creator);
}
/**新建带状态内容的JSONObject
* @param code
* @param msg
* @return
*/
public static JSONObject newResult(int code, String msg) {
return extendResult(null, code, msg);
}
/**添加JSONObject的状态内容,一般用于错误提示结果
* @param object
* @param code
* @param msg
* @return
*/
public static JSONObject extendResult(JSONObject object, int code, String msg) {
if (object == null) {
object = new JSONObject(true);
}
if (object.containsKey(JSONResponse.KEY_OK) == false) {
object.put(JSONResponse.KEY_OK, JSONResponse.isSuccess(code));
}
if (object.containsKey(JSONResponse.KEY_CODE) == false) {
object.put(JSONResponse.KEY_CODE, code);
}
String m = StringUtil.getString(object.getString(JSONResponse.KEY_MSG));
if (m.isEmpty() == false) {
msg = m + " ;\n " + StringUtil.getString(msg);
}
object.put(JSONResponse.KEY_MSG, msg);
return object;
}
/**添加请求成功的状态内容
* @param object
* @return
*/
public static JSONObject extendSuccessResult(JSONObject object) {
return extendResult(object, JSONResponse.CODE_SUCCESS, JSONResponse.MSG_SUCCEED);
}
/**获取请求成功的状态内容
* @return
*/
public static JSONObject newSuccessResult() {
return newResult(JSONResponse.CODE_SUCCESS, JSONResponse.MSG_SUCCEED);
}
/**添加请求成功的状态内容
* @param object
* @return
*/
public static JSONObject extendErrorResult(JSONObject object, Exception e) {
JSONObject error = newErrorResult(e);
return extendResult(object, error.getIntValue(JSONResponse.KEY_CODE), error.getString(JSONResponse.KEY_MSG));
}
/**新建错误状态内容
* @param e
* @return
*/
public static JSONObject newErrorResult(Exception e) {
if (e != null) {
e.printStackTrace();
int code;
if (e instanceof UnsupportedEncodingException) {
code = JSONResponse.CODE_UNSUPPORTED_ENCODING;
}
else if (e instanceof IllegalAccessException) {
code = JSONResponse.CODE_ILLEGAL_ACCESS;
}
else if (e instanceof UnsupportedOperationException) {
code = JSONResponse.CODE_UNSUPPORTED_OPERATION;
}
else if (e instanceof NotExistException) {
code = JSONResponse.CODE_NOT_FOUND;
}
else if (e instanceof IllegalArgumentException) {
code = JSONResponse.CODE_ILLEGAL_ARGUMENT;
}
else if (e instanceof NotLoggedInException) {
code = JSONResponse.CODE_NOT_LOGGED_IN;
}
else if (e instanceof TimeoutException) {
code = JSONResponse.CODE_TIME_OUT;
}
else if (e instanceof ConflictException) {
code = JSONResponse.CODE_CONFLICT;
}
else if (e instanceof ConditionErrorException) {
code = JSONResponse.CODE_CONDITION_ERROR;
}
else if (e instanceof UnsupportedDataTypeException) {
code = JSONResponse.CODE_UNSUPPORTED_TYPE;
}
else if (e instanceof OutOfRangeException) {
code = JSONResponse.CODE_OUT_OF_RANGE;
}
else if (e instanceof NullPointerException) {
code = JSONResponse.CODE_NULL_POINTER;
}
else {
code = JSONResponse.CODE_SERVER_ERROR;
}
return newResult(code, e.getMessage());
}
return newResult(JSONResponse.CODE_SERVER_ERROR, JSONResponse.MSG_SERVER_ERROR);
}
//TODO 启动时一次性加载Request所有内容,作为初始化。
/**获取正确的请求,非GET请求必须是服务器指定的
* @param method
* @param request
* @return
* @throws Exception
*/
@Override
public JSONObject parseCorrectRequest() throws Exception {
setTag(requestObject.getString(JSONRequest.KEY_TAG));
setVersion(requestObject.getIntValue(JSONRequest.KEY_VERSION));
requestObject.remove(JSONRequest.KEY_TAG);
requestObject.remove(JSONRequest.KEY_VERSION);
return parseCorrectRequest(requestMethod, tag, version, "", requestObject, getMaxUpdateCount(), this);
}
//TODO 优化性能!
/**获取正确的返回结果
* @param method
* @param response
* @return
* @throws Exception
*/
@Override
public JSONObject parseCorrectResponse(String table, JSONObject response) throws Exception {
// Log.d(TAG, "getCorrectResponse method = " + method + "; table = " + table);
// if (response == null || response.isEmpty()) {//避免无效空result:{}添加内容后变有效
// Log.e(TAG, "getCorrectResponse response == null || response.isEmpty() >> return response;");
return response;
// }
//
// JSONObject target = apijson.JSONObject.isTableKey(table) == false
// ? new JSONObject() : getStructure(method, "Response", "model", table);
//
// return MethodStructure.parseResponse(method, table, target, response, new OnParseCallback() {
//
// @Override
// protected JSONObject onParseJSONObject(String key, JSONObject tobj, JSONObject robj) throws Exception {
// return getCorrectResponse(method, key, robj);
// }
// });
}
/**获取Request或Response内指定JSON结构
* @param table
* @param method
* @param tag
* @param version
* @return
* @throws Exception
*/
@Override
public JSONObject getStructure(@NotNull String table, String method, String tag, int version) throws Exception {
// TODO 目前只使用 Request 而不使用 Response,所以这里写死用 REQUEST_MAP,以后可能 Response 表也会与 Request 表合并,用字段来区分
String cacheKey = AbstractVerifier.getCacheKeyForRequest(method, tag);
SortedMap<Integer, JSONObject> versionedMap = AbstractVerifier.REQUEST_MAP.get(cacheKey);
JSONObject result = versionedMap == null ? null : versionedMap.get(Integer.valueOf(version));
if (result == null) { // version <= 0 时使用最新,version > 0 时使用 > version 的最接近版本(最小版本)
Set<Entry<Integer, JSONObject>> set = versionedMap == null ? null : versionedMap.entrySet();
if (set != null && set.isEmpty() == false) {
Entry<Integer, JSONObject> maxEntry = null;
for (Entry<Integer, JSONObject> entry : set) {
if (entry == null || entry.getKey() == null || entry.getValue() == null) {
continue;
}
if (version <= 0 || version == entry.getKey()) { // 这里应该不会出现相等,因为上面 versionedMap.get(Integer.valueOf(version))
maxEntry = entry;
break;
}
if (entry.getKey() < version) {
break;
}
maxEntry = entry;
}
result = maxEntry == null ? null : maxEntry.getValue();
}
if (result != null) { // 加快下次查询,查到值的话组合情况其实是有限的,不属于恶意请求
if (versionedMap == null) {
versionedMap = new TreeMap<>((o1, o2) -> {
return o2 == null ? -1 : o2.compareTo(o1); // 降序
});
}
versionedMap.put(Integer.valueOf(version), result);
AbstractVerifier.REQUEST_MAP.put(cacheKey, versionedMap);
}
}
if (result == null) {
if (AbstractVerifier.REQUEST_MAP.isEmpty() == false) {
return null; // 已使用 REQUEST_MAP 缓存全部,但没查到
}
//获取指定的JSON结构 <<<<<<<<<<<<<<
SQLConfig config = createSQLConfig().setMethod(GET).setTable(table);
config.setPrepared(false);
config.setColumn(Arrays.asList("structure"));
Map<String, Object> where = new HashMap<String, Object>();
where.put("method", method);
where.put(JSONRequest.KEY_TAG, tag);
if (version > 0) {
where.put(JSONRequest.KEY_VERSION + "{}", ">=" + version);
}
config.setWhere(where);
config.setOrder(JSONRequest.KEY_VERSION + (version > 0 ? "+" : "-"));
config.setCount(1);
//too many connections error: 不try-catch,可以让客户端看到是服务器内部异常
result = getSQLExecutor().execute(config, false);
// version, method, tag 组合情况太多了,JDK 里又没有 LRUCache,所以要么启动时一次性缓存全部后面只用缓存,要么每次都查数据库
// versionedMap.put(Integer.valueOf(version), result);
// AbstractVerifier.REQUEST_MAP.put(cacheKey, versionedMap);
}
return getJSONObject(result, "structure"); //解决返回值套了一层 "structure":{}
}
// protected SQLConfig itemConfig;
/**获取单个对象,该对象处于parentObject内
* @param parentPath parentObject的路径
* @param name parentObject的key
* @param request parentObject的value
* @param config for array item
* @return
* @throws Exception
*/
@Override
public JSONObject onObjectParse(final JSONObject request
, String parentPath, String name, final SQLConfig arrayConfig, boolean isSubquery) throws Exception {
if (Log.DEBUG) {
Log.i(TAG, "\ngetObject: parentPath = " + parentPath
+ ";\n name = " + name + "; request = " + JSON.toJSONString(request));
}
if (request == null) {// Moment:{} || request.isEmpty()) {//key-value条件
return null;
}
int type = arrayConfig == null ? 0 : arrayConfig.getType();
String[] arr = StringUtil.split(parentPath, "/");
if (arrayConfig == null || arrayConfig.getPosition() == 0) {
int d = arr == null ? 1 : arr.length + 1;
if (queryDepth < d) {
queryDepth = d;
int maxQueryDepth = getMaxQueryDepth();
if (queryDepth > maxQueryDepth) {
throw new IllegalArgumentException(parentPath + "/" + name + ":{} 的深度(或者说层级) 为 " + queryDepth + " 已超限,必须在 1-" + maxQueryDepth + " 内 !");
}
}
}
ObjectParser op = createObjectParser(request, parentPath, name, arrayConfig, isSubquery).parse();
JSONObject response = null;
if (op != null) {//TODO SQL查询结果为空时,functionMap和customMap还有没有意义?
if (arrayConfig == null) {//Common
response = op.setSQLConfig().executeSQL().response();
}
else {//Array Item Child
int query = arrayConfig.getQuery();
//total 这里不能用arrayConfig.getType(),因为在createObjectParser.onChildParse传到onObjectParse时已被改掉
if (type == SQLConfig.TYPE_ITEM_CHILD_0 && query != JSONRequest.QUERY_TABLE
&& arrayConfig.getPosition() == 0) {
JSONObject rp = op.setMethod(RequestMethod.HEAD).setSQLConfig().executeSQL().getSqlReponse();
if (rp != null) {
int index = parentPath.lastIndexOf("]/");
if (index >= 0) {
int total = rp.getIntValue(JSONResponse.KEY_COUNT);
String pathPrefix = parentPath.substring(0, index) + "]/";
putQueryResult(pathPrefix + JSONResponse.KEY_TOTAL, total);
//详细的分页信息,主要为 PC 端提供
int count = arrayConfig.getCount();
int page = arrayConfig.getPage();
int max = (int) ((total - 1)/count);
if (max < 0) {
max = 0;
}
JSONObject pagination = new JSONObject(true);
pagination.put(JSONResponse.KEY_TOTAL, total);
pagination.put(JSONRequest.KEY_COUNT, count);
pagination.put(JSONRequest.KEY_PAGE, page);
pagination.put(JSONResponse.KEY_MAX, max);
pagination.put(JSONResponse.KEY_MORE, page < max);
pagination.put(JSONResponse.KEY_FIRST, page == 0);
pagination.put(JSONResponse.KEY_LAST, page == max);
putQueryResult(pathPrefix + JSONResponse.KEY_INFO, pagination);
if (total <= count*page) {
query = JSONRequest.QUERY_TOTAL;//数量不够了,不再往后查询
}
}
}
op.setMethod(requestMethod);
}
//Table
if (query == JSONRequest.QUERY_TOTAL) {
response = null;//不再往后查询
} else {
response = op
.setSQLConfig(arrayConfig.getCount(), arrayConfig.getPage(), arrayConfig.getPosition())
.executeSQL()
.response();
// itemConfig = op.getConfig();
}
}
op.recycle();
op = null;
}
return response;
}
/**获取对象数组,该对象数组处于parentObject内
* @param parentPath parentObject的路径
* @param name parentObject的key
* @param request parentObject的value
* @return
* @throws Exception
*/
@Override
public JSONArray onArrayParse(JSONObject request, String parentPath, String name, boolean isSubquery) throws Exception {
if (Log.DEBUG) {
Log.i(TAG, "\n\n\n onArrayParse parentPath = " + parentPath
+ "; name = " + name + "; request = " + JSON.toJSONString(request));
}
//不能允许GETS,否则会被通过"[]":{"@role":"ADMIN"},"Table":{},"tag":"Table"绕过权限并能批量查询
if (isSubquery == false && RequestMethod.isGetMethod(requestMethod, false) == false) {
throw new UnsupportedOperationException("key[]:{}只支持GET方法!不允许传 " + name + ":{} !");
}
if (request == null || request.isEmpty()) {//jsonKey-jsonValue条件
return null;
}
String path = getAbsPath(parentPath, name);
//不能改变,因为后面可能继续用到,导致1以上都改变 []:{0:{Comment[]:{0:{Comment:{}},1:{...},...}},1:{...},...}
final String query = request.getString(JSONRequest.KEY_QUERY);
final Integer count = request.getInteger(JSONRequest.KEY_COUNT); //TODO 如果不想用默认数量可以改成 getIntValue(JSONRequest.KEY_COUNT);
final int page = request.getIntValue(JSONRequest.KEY_PAGE);
final Object join = request.get(JSONRequest.KEY_JOIN);
int query2;
if (query == null) {
query2 = JSONRequest.QUERY_TABLE;
}
else {
switch (query) {
case "0":
case JSONRequest.QUERY_TABLE_STRING:
query2 = JSONRequest.QUERY_TABLE;
break;
case "1":
case JSONRequest.QUERY_TOTAL_STRING:
query2 = JSONRequest.QUERY_TOTAL;
break;
case "2":
case JSONRequest.QUERY_ALL_STRING:
query2 = JSONRequest.QUERY_ALL;
break;
default:
throw new IllegalArgumentException(path + "/" + JSONRequest.KEY_QUERY + ":value 中 value 的值不合法!必须在 [0,1,2] 或 [TABLE, TOTAL, ALL] 内 !");
}
}
int maxPage = getMaxQueryPage();
if (page < 0 || page > maxPage) {
throw new IllegalArgumentException(path + "/" + JSONRequest.KEY_PAGE + ":value 中 value 的值不合法!必须在 0-" + maxPage + " 内 !");
}
//不用total限制数量了,只用中断机制,total只在query = 1,2的时候才获取
int count2 = isSubquery || count != null ? (count == null ? 0 : count) : getDefaultQueryCount();
int max = isSubquery ? count2 : getMaxQueryCount();
if (count2 < 0 || count2 > max) {
throw new IllegalArgumentException(path + "/" + JSONRequest.KEY_COUNT + ":value 中 value 的值不合法!必须在 0-" + max + " 内 !");
}
request.remove(JSONRequest.KEY_QUERY);
request.remove(JSONRequest.KEY_COUNT);
request.remove(JSONRequest.KEY_PAGE);
request.remove(JSONRequest.KEY_JOIN);
Log.d(TAG, "onArrayParse query = " + query + "; count = " + count + "; page = " + page + "; join = " + join);
if (request.isEmpty()) { // 如果条件成立,说明所有的 parentPath/name:request 中request都无效!!! 后续都不执行,没必要还原数组关键词浪费性能
Log.e(TAG, "onArrayParse request.isEmpty() >> return null;");
return null;
}
JSONArray response = null;
try {
int size = count2 == 0 ? max : count2;//count为每页数量,size为第page页实际数量,max(size) = count
Log.d(TAG, "onArrayParse size = " + size + "; page = " + page);
//key[]:{Table:{}}中key equals Table时 提取Table
int index = isSubquery || name == null ? -1 : name.lastIndexOf("[]");
String childPath = index <= 0 ? null : Pair.parseEntry(name.substring(0, index), true).getKey(); // Table-key1-key2...
//判断第一个key,即Table是否存在,如果存在就提取
String[] childKeys = StringUtil.split(childPath, "-", false);
if (childKeys == null || childKeys.length <= 0 || request.containsKey(childKeys[0]) == false) {
childKeys = null;
}
//Table<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
response = new JSONArray();
SQLConfig config = createSQLConfig()
.setMethod(requestMethod)
.setCount(size)
.setPage(page)
.setQuery(query2)
.setJoinList(onJoinParse(join, request));
JSONObject parent;
//生成size个
for (int i = 0; i < (isSubquery ? 1 : size); i++) {
parent = onObjectParse(request, isSubquery ? parentPath : path, isSubquery ? name : "" + i, config.setType(SQLConfig.TYPE_ITEM).setPosition(i), isSubquery);
if (parent == null || parent.isEmpty()) {
break;
}
//key[]:{Table:{}}中key equals Table时 提取Table
response.add(getValue(parent, childKeys)); //null有意义
}
//Table>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/*
* 支持引用取值后的数组
{
"User-id[]": {
"User": {
"contactIdList<>": 82002
}
},
"Moment-userId[]": {
"Moment": {
"userId{}@": "User-id[]"
}
}
}
*/
Object fo = childKeys == null || response.isEmpty() ? null : response.get(0);
if (fo instanceof Boolean || fo instanceof Number || fo instanceof String) { //[{}] 和 [[]] 都没意义
putQueryResult(path, response);
}
} finally {
//后面还可能用到,要还原
request.put(JSONRequest.KEY_QUERY, query);
request.put(JSONRequest.KEY_COUNT, count);
request.put(JSONRequest.KEY_PAGE, page);