-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathAbstractObjectParser.java
executable file
·899 lines (740 loc) · 26.8 KB
/
AbstractObjectParser.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
/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon/APIJSON)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this 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.*/
package zuo.biao.apijson.server;
import static zuo.biao.apijson.JSONObject.KEY_COMBINE;
import static zuo.biao.apijson.JSONObject.KEY_DROP;
import static zuo.biao.apijson.JSONObject.KEY_TRY;
import static zuo.biao.apijson.RequestMethod.PUT;
import static zuo.biao.apijson.server.SQLConfig.TYPE_ITEM;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import zuo.biao.apijson.Log;
import zuo.biao.apijson.NotNull;
import zuo.biao.apijson.RequestMethod;
import zuo.biao.apijson.StringUtil;
import zuo.biao.apijson.server.RemoteFunction.FunctionBean;
import zuo.biao.apijson.server.exception.ConflictException;
import zuo.biao.apijson.server.exception.NotExistException;
/**简化Parser,getObject和getArray(getArrayConfig)都能用
* @author Lemon
*/
public abstract class AbstractObjectParser implements ObjectParser {
private static final String TAG = "AbstractObjectParser";
@NotNull
protected Parser<?> parser;
public AbstractObjectParser setParser(Parser<?> parser) {
this.parser = parser;
return this;
}
protected JSONObject request;//不用final是为了recycle
protected String parentPath;//不用final是为了recycle
protected SQLConfig arrayConfig;//不用final是为了recycle
protected boolean isSubquery;
protected final int type;
protected final List<Join> joinList;
protected final boolean isTable;
protected final String path;
protected final String table;
protected final String alias;
protected final boolean tri;
/**
* TODO Parser内要不因为 非 TYPE_ITEM_CHILD_0 的Table 为空导致后续中断。
*/
protected final boolean drop;
/**for single object
* @param parentPath
* @param request
* @param name
* @throws Exception
*/
public AbstractObjectParser(@NotNull JSONObject request, String parentPath, String name, SQLConfig arrayConfig, boolean isSubquery) throws Exception {
if (request == null) {
throw new IllegalArgumentException(TAG + ".ObjectParser request == null!!!");
}
this.request = request;
this.parentPath = parentPath;
this.arrayConfig = arrayConfig;
this.isSubquery = isSubquery;
this.type = arrayConfig == null ? 0 : arrayConfig.getType();
this.joinList = arrayConfig == null ? null : arrayConfig.getJoinList();
this.path = AbstractParser.getAbsPath(parentPath, name);
zuo.biao.apijson.server.Entry<String, String> entry = Pair.parseEntry(name, true);
this.table = entry.getKey();
this.alias = entry.getValue();
this.isTable = zuo.biao.apijson.JSONObject.isTableKey(table);
this.objectCount = 0;
this.arrayCount = 0;
boolean isEmpty = request.isEmpty();//empty有效 User:{}
if (isEmpty) {
this.tri = false;
this.drop = false;
}
else {
this.tri = request.getBooleanValue(KEY_TRY);
this.drop = request.getBooleanValue(KEY_DROP);
request.remove(KEY_TRY);
request.remove(KEY_DROP);
}
Log.d(TAG, "AbstractObjectParser table = " + table + "; isTable = " + isTable);
Log.d(TAG, "AbstractObjectParser isEmpty = " + isEmpty + "; tri = " + tri + "; drop = " + drop);
}
public static final Map<String, Pattern> COMPILE_MAP;
static {
COMPILE_MAP = new HashMap<String, Pattern>();
}
private boolean invalidate = false;
public void invalidate() {
invalidate = true;
}
public boolean isInvalidate() {
return invalidate;
}
private boolean breakParse = false;
public void breakParse() {
breakParse = true;
}
public boolean isBreakParse() {
return breakParse || isInvalidate();
}
protected JSONObject response;
protected JSONObject sqlRequest;
protected JSONObject sqlReponse;
/**
* 自定义关键词
*/
protected Map<String, Object> customMap;
/**
* 远程函数
* {"-":{ "key-()":value }, "0":{ "key()":value }, "+":{ "key+()":value } }
* - : 在executeSQL前解析
* 0 : 在executeSQL后、onChildParse前解析
* + : 在onChildParse后解析
*/
protected Map<String, Map<String, String>> functionMap;
/**
* 子对象
*/
protected Map<String, JSONObject> childMap;
private int objectCount;
private int arrayCount;
/**解析成员
* response重新赋值
* @return null or this
* @throws Exception
*/
@Override
public AbstractObjectParser parse() throws Exception {
if (isInvalidate() == false) {
breakParse = false;
response = new JSONObject(true);//must init
sqlRequest = new JSONObject(true);//must init
sqlReponse = null;//must init
customMap = null;//must init
functionMap = null;//must init
childMap = null;//must init
Set<Entry<String, Object>> set = new LinkedHashSet<Entry<String, Object>>(request.entrySet());
if (set != null && set.isEmpty() == false) {//判断换取少几个变量的初始化是否值得?
if (isTable) {//非Table下必须保证原有顺序!否则 count,page 会丢, total@:"/[]/total" 会在[]:{}前执行!
customMap = new LinkedHashMap<String, Object>();
childMap = new LinkedHashMap<String, JSONObject>();
}
functionMap = new LinkedHashMap<String, Map<String, String>>();//必须执行
//条件<<<<<<<<<<<<<<<<<<<
List<String> whereList = null;
if (method == PUT) { //这里只有PUTArray需要处理 || method == DELETE) {
String[] combine = StringUtil.split(request.getString(KEY_COMBINE));
if (combine != null) {
String w;
for (int i = 0; i < combine.length; i++) { //去除 &,|,! 前缀
w = combine[i];
if (w != null && (w.startsWith("&") || w.startsWith("|") || w.startsWith("!"))) {
combine[i] = w.substring(1);
}
}
}
//Arrays.asList()返回值不支持add方法!
whereList = new ArrayList<String>(Arrays.asList(combine != null ? combine : new String[]{}));
whereList.add(zuo.biao.apijson.JSONRequest.KEY_ID);
whereList.add(zuo.biao.apijson.JSONRequest.KEY_ID_IN);
}
//条件>>>>>>>>>>>>>>>>>>>
String key;
Object value;
int index = 0;
for (Entry<String, Object> entry : set) {
if (isBreakParse()) {
break;
}
value = entry.getValue();
if (value == null) {
continue;
}
key = entry.getKey();
try {
if (value instanceof JSONObject && key.startsWith("@") == false && key.endsWith("@") == false) {//JSONObject,往下一级提取
if (childMap != null) {//添加到childMap,最后再解析
childMap.put(key, (JSONObject)value);
}
else {//直接解析并替换原来的,[]:{} 内必须直接解析,否则会因为丢掉count等属性,并且total@:"/[]/total"必须在[]:{} 后!
response.put(key, onChildParse(index, key, (JSONObject)value));
index ++;
}
} else if (value instanceof JSONArray && method == POST &&
key.startsWith("@") == false && key.endsWith("@") == false) {//JSONArray,批量新增,往下一级提取
JSONArray valueArray = (JSONArray)value;
for (int i = 0; i < valueArray.size(); i++) {
if (childMap != null) {//添加到childMap,最后再解析
childMap.put(key, valueArray.getJSONObject(i));
}
else {//直接解析并替换原来的,[]:{} 内必须直接解析,否则会因为丢掉count等属性,并且total@:"/[]/total"必须在[]:{} 后!
JSONObject result = (JSONObject)onChildParse(index, key, valueArray.getJSONObject(i));
//合并结果
JSONObject before = (JSONObject)response.get(key);
if(result.get("code").equals(200)){
if(before!=null){
before.put("count",before.getInteger("count")+result.getInteger("count"));
response.put(key, before);
}else{
response.put(key, result);
}
} else {
//只要有一条失败,则抛出异常,全部失败
throw new RuntimeException(key + "," + valueArray.getJSONObject(i) +",新增失败!");
}
}
}
index ++;
} else if (method == PUT && value instanceof JSONArray
&& (whereList == null || whereList.contains(key) == false)) {//PUT JSONArray
onPUTArrayParse(key, (JSONArray) value);
}
else {//JSONArray或其它Object,直接填充
if (onParse(key, value) == false) {
invalidate();
}
}
} catch (Exception e) {
if (tri == false) {
throw e;//不忽略错误,抛异常
}
invalidate();//忽略错误,还原request
}
}
//非Table内的函数会被滞后在onChildParse后调用! onFunctionResponse("-");
}
if (isTable) {
if (sqlRequest.get(JSONRequest.KEY_DATABASE) == null && parser.getGlobleDatabase() != null) {
sqlRequest.put(JSONRequest.KEY_DATABASE, parser.getGlobleDatabase());
}
if (sqlRequest.get(JSONRequest.KEY_SCHEMA) == null && parser.getGlobleSchema() != null) {
sqlRequest.put(JSONRequest.KEY_SCHEMA, parser.getGlobleSchema());
}
if (isSubquery == false) { //解决 SQL 语法报错,子查询不能 EXPLAIN
if (sqlRequest.get(JSONRequest.KEY_EXPLAIN) == null && parser.getGlobleExplain() != null) {
sqlRequest.put(JSONRequest.KEY_EXPLAIN, parser.getGlobleExplain());
}
if (sqlRequest.get(JSONRequest.KEY_CACHE) == null && parser.getGlobleCache() != null) {
sqlRequest.put(JSONRequest.KEY_CACHE, parser.getGlobleCache());
}
}
}
}
if (isInvalidate()) {
recycle();
return null;
}
return this;
}
/**解析普通成员
* @param key
* @param value
* @return whether parse succeed
*/
@Override
public boolean onParse(@NotNull String key, @NotNull Object value) throws Exception {
if (key.endsWith("@")) {//StringUtil.isPath((String) value)) {
if (value instanceof JSONObject) { // SQL 子查询对象,JSONObject -> SQLConfig.getSQL
String replaceKey = key.substring(0, key.length() - 1);//key{}@ getRealKey
JSONObject subquery = (JSONObject) value;
String range = subquery.getString(JSONRequest.KEY_SUBQUERY_RANGE);
if (range != null && JSONRequest.SUBQUERY_RANGE_ALL.equals(range) == false && JSONRequest.SUBQUERY_RANGE_ANY.equals(range) == false) {
throw new IllegalArgumentException("子查询 " + path + "/" + key + ":{ range:value } 中 value 只能为 [" + JSONRequest.SUBQUERY_RANGE_ALL + ", " + JSONRequest.SUBQUERY_RANGE_ANY + "] 中的一个!");
}
JSONArray arr = parser.onArrayParse(subquery, path, key, true);
JSONObject obj = arr == null || arr.isEmpty() ? null : arr.getJSONObject(0);
if (obj == null) {
throw new Exception("服务器内部错误,解析子查询 " + path + "/" + key + ":{ } 为 Subquery 对象失败!");
}
String from = subquery.getString(JSONRequest.KEY_SUBQUERY_FROM);
JSONObject arrObj = from == null ? null : obj.getJSONObject(from);
if (arrObj == null) {
throw new IllegalArgumentException("子查询 " + path + "/" + key + ":{ from:value } 中 value 对应的主表对象 " + from + ":{} 不存在!");
}
//
SQLConfig cfg = (SQLConfig) arrObj.get(AbstractParser.KEY_CONFIG);
if (cfg == null) {
throw new NotExistException(TAG + ".onParse cfg == null");
}
Subquery s = new Subquery();
s.setPath(path);
s.setOriginKey(key);
s.setOriginValue(subquery);
s.setFrom(from);
s.setRange(range);
s.setKey(replaceKey);
s.setConfig(cfg);
key = replaceKey;
value = s; //(range == null || range.isEmpty() ? "" : "range") + "(" + cfg.getSQL(false) + ") ";
parser.putQueryResult(AbstractParser.getAbsPath(path, key), s); //字符串引用保证不了安全性 parser.getSQL(cfg));
}
else if (value instanceof String) { // 引用赋值路径
// System.out.println("getObject key.endsWith(@) >> parseRelation = " + parseRelation);
String replaceKey = key.substring(0, key.length() - 1);//key{}@ getRealKey
String targetPath = AbstractParser.getValuePath(type == TYPE_ITEM
? path : parentPath, new String((String) value));
//先尝试获取,尽量保留缺省依赖路径,这样就不需要担心路径改变
Object target = onReferenceParse(targetPath);
Log.i(TAG, "onParse targetPath = " + targetPath + "; target = " + target);
if (target == null) {//String#equals(null)会出错
Log.d(TAG, "onParse target == null >> continue;");
return true;
}
if (target instanceof Map) { //target可能是从requestObject里取出的 {}
Log.d(TAG, "onParse target instanceof Map >> continue;");
return false;
}
if (targetPath.equals(target)) {//必须valuePath和保证getValueByPath传进去的一致!
Log.d(TAG, "onParse targetPath.equals(target) >>");
//非查询关键词 @key 不影响查询,直接跳过
if (isTable && (key.startsWith("@") == false || JSONRequest.TABLE_KEY_LIST.contains(key))) {
Log.e(TAG, "onParse isTable && (key.startsWith(@) == false"
+ " || JSONRequest.TABLE_KEY_LIST.contains(key)) >> return null;");
return false;//获取不到就不用再做无效的query了。不考虑 Table:{Table:{}}嵌套
} else {
Log.d(TAG, "onParse isTable(table) == false >> continue;");
return true;//舍去,对Table无影响
}
}
//直接替换原来的key@:path为key:target
Log.i(TAG, "onParse >> key = replaceKey; value = target;");
key = replaceKey;
value = target;
Log.d(TAG, "onParse key = " + key + "; value = " + value);
}
else {
throw new IllegalArgumentException(path + "/" + key + ":value 中 value 必须为 依赖路径String 或 SQL子查询JSONObject !");
}
}
if (key.endsWith("()")) {
if (value instanceof String == false) {
throw new IllegalArgumentException(path + "/" + key + ":value 中 value 必须为函数String!");
}
String k = key.substring(0, key.length() - 2);
String type; //远程函数比较少用,一般一个Table:{}内用到也就一两个,所以这里用 "-","0","+" 更直观,转用 -1,0,1 对性能提升不大。
if (k.endsWith("-")) { //不能封装到functionMap后批量执行,否则会导致非Table内的 key-():function() 在onChildParse后执行!
type = "-";
k = k.substring(0, k.length() - 1);
parseFunction(request, k, (String) value);
}
else {
if (k.endsWith("+")) {
type = "+";
k = k.substring(0, k.length() - 1);
}
else {
type = "0";
}
//远程函数比较少用,一般一个Table:{}内用到也就一两个,所以这里循环里new出来对性能影响不大。
Map<String, String> map = functionMap.get(type);
if (map == null) {
map = new LinkedHashMap<>();
}
map.put(k, (String) value);
functionMap.put(type, map);
}
}
else if (isTable && key.startsWith("@") && JSONRequest.TABLE_KEY_LIST.contains(key) == false) {
customMap.put(key, value);
}
else {
sqlRequest.put(key, value);
}
return true;
}
/**
* @param key
* @param value
* @param isFirst
* @return
* @throws Exception
*/
@Override
public JSON onChildParse(int index, String key, JSONObject value) throws Exception {
boolean isFirst = index <= 0;
boolean isMain = isFirst && type == TYPE_ITEM;
JSON child;
boolean isEmpty;
if (zuo.biao.apijson.JSONObject.isArrayKey(key)) {//APIJSON Array
if (isMain) {
throw new IllegalArgumentException(parentPath + "/" + key + ":{} 不合法!"
+ "数组 []:{} 中第一个 key:{} 必须是主表 TableKey:{} !不能为 arrayKey[]:{} !");
}
if (arrayConfig == null || arrayConfig.getPosition() == 0) {
arrayCount ++;
int maxArrayCount = parser.getMaxArrayCount();
if (arrayCount > maxArrayCount) {
throw new IllegalArgumentException(path + " 内截至 " + key + ":{} 时数组对象 key[]:{} 的数量达到 " + arrayCount + " 已超限,必须在 0-" + maxArrayCount + " 内 !");
}
}
child = parser.onArrayParse(value, path, key, isSubquery);
isEmpty = child == null || ((JSONArray) child).isEmpty();
}
else {//APIJSON Object
boolean isTableKey = JSONRequest.isTableKey(Pair.parseEntry(key, true).getKey());
if (type == TYPE_ITEM && isTableKey == false) {
throw new IllegalArgumentException(parentPath + "/" + key + ":{} 不合法!"
+ "数组 []:{} 中每个 key:{} 都必须是表 TableKey:{} 或 数组 arrayKey[]:{} !");
}
if (//避免使用 "test":{"Test":{}} 绕过限制,实现查询爆炸 isTableKey &&
(arrayConfig == null || arrayConfig.getPosition() == 0)) {
objectCount ++;
int maxObjectCount = parser.getMaxObjectCount();
if (objectCount > maxObjectCount) {
throw new IllegalArgumentException(path + " 内截至 " + key + ":{} 时对象 key:{} 的数量达到 " + objectCount + " 已超限,必须在 0-" + maxObjectCount + " 内 !");
}
}
child = parser.onObjectParse(value, path, key, isMain ? arrayConfig.setType(SQLConfig.TYPE_ITEM_CHILD_0) : null, isSubquery);
isEmpty = child == null || ((JSONObject) child).isEmpty();
if (isFirst && isEmpty) {
invalidate();
}
}
Log.i(TAG, "onChildParse ObjectParser.onParse key = " + key + "; child = " + child);
return isEmpty ? null : child;//只添加! isChildEmpty的值,可能数据库返回数据不够count
}
//TODO 改用 MySQL json_add,json_remove,json_contains 等函数!
/**PUT key:[]
* @param key
* @param array
* @throws Exception
*/
@Override
public void onPUTArrayParse(@NotNull String key, @NotNull JSONArray array) throws Exception {
if (isTable == false || array.isEmpty()) {
Log.e(TAG, "onPUTArrayParse isTable == false || array == null || array.isEmpty() >> return;");
return;
}
int putType = 0;
if (key.endsWith("+")) {//add
putType = 1;
} else if (key.endsWith("-")) {//remove
putType = 2;
} else {//replace
// throw new IllegalAccessException("PUT " + path + ", PUT Array不允许 " + key +
// " 这种没有 + 或 - 结尾的key!不允许整个替换掉原来的Array!");
}
String realKey = AbstractSQLConfig.getRealKey(method, key, false, false, "`"); //FIXME PG 是 "
//GET > add all 或 remove all > PUT > remove key
//GET <<<<<<<<<<<<<<<<<<<<<<<<<
JSONObject rq = new JSONObject();
rq.put(JSONRequest.KEY_ID, request.get(JSONRequest.KEY_ID));
rq.put(JSONRequest.KEY_COLUMN, realKey);
JSONObject rp = parseResponse(RequestMethod.GET, table, null, rq, null, false);
//GET >>>>>>>>>>>>>>>>>>>>>>>>>
//add all 或 remove all <<<<<<<<<<<<<<<<<<<<<<<<<
JSONArray targetArray = rp == null ? null : rp.getJSONArray(realKey);
if (targetArray == null) {
targetArray = new JSONArray();
}
for (Object obj : array) {
if (obj == null) {
continue;
}
if (putType == 1) {
if (targetArray.contains(obj)) {
throw new ConflictException("PUT " + path + ", " + realKey + ":" + obj + " 已存在!");
}
targetArray.add(obj);
} else if (putType == 2) {
if (targetArray.contains(obj) == false) {
throw new NullPointerException("PUT " + path + ", " + realKey + ":" + obj + " 不存在!");
}
targetArray.remove(obj);
}
}
//add all 或 remove all >>>>>>>>>>>>>>>>>>>>>>>>>
//PUT <<<<<<<<<<<<<<<<<<<<<<<<<
sqlRequest.put(realKey, targetArray);
//PUT >>>>>>>>>>>>>>>>>>>>>>>>>
}
@Override
public JSONObject parseResponse(RequestMethod method, String table, String alias, JSONObject request, List<Join> joinList, boolean isProcedure) throws Exception {
SQLConfig config = newSQLConfig(method, table, alias, request, joinList, isProcedure);
return parseResponse(config, isProcedure);
}
@Override
public JSONObject parseResponse(SQLConfig config, boolean isProcedure) throws Exception {
if (parser.getSQLExecutor() == null) {
parser.createSQLExecutor();
}
return parser.getSQLExecutor().execute(config, isProcedure);
}
@Override
public SQLConfig newSQLConfig(boolean isProcedure) throws Exception {
return newSQLConfig(method, table, alias, sqlRequest, joinList, isProcedure);
}
/**SQL 配置,for single object
* @return {@link #setSQLConfig(int, int, int)}
* @throws Exception
*/
@Override
public AbstractObjectParser setSQLConfig() throws Exception {
return setSQLConfig(1, 0, 0);
}
@Override
public AbstractObjectParser setSQLConfig(int count, int page, int position) throws Exception {
if (isTable == false) {
return this;
}
if (sqlConfig == null) {
try {
sqlConfig = newSQLConfig(false);
}
catch (NotExistException e) {
e.printStackTrace();
return this;
}
}
sqlConfig.setCount(count).setPage(page).setPosition(position);
parser.onVerifyRole(sqlConfig);
return this;
}
protected SQLConfig sqlConfig = null;//array item复用
/**SQL查询,for array item
* @param count
* @param page
* @param position
* @return this
* @throws Exception
*/
@Override
public AbstractObjectParser executeSQL() throws Exception {
//执行SQL操作数据库
if (isTable == false) {//提高性能
sqlReponse = new JSONObject(sqlRequest);
} else {
try {
sqlReponse = onSQLExecute();
}
catch (NotExistException e) {
// Log.e(TAG, "getObject try { response = getSQLObject(config2); } catch (Exception e) {");
// if (e instanceof NotExistException) {//非严重异常,有时候只是数据不存在
// // e.printStackTrace();
sqlReponse = null;//内部吃掉异常,put到最外层
// requestObject.put(JSONResponse.KEY_MSG
// , StringUtil.getString(requestObject.get(JSONResponse.KEY_MSG)
// + "; query " + path + " cath NotExistException:"
// + newErrorResult(e).getString(JSONResponse.KEY_MSG)));
// } else {
// throw e;
// }
}
if (drop) {//丢弃Table,只为了向下提供条件
sqlReponse = null;
}
}
return this;
}
/**
* @return response
* @throws Exception
*/
@Override
public JSONObject response() throws Exception {
if (sqlReponse == null || sqlReponse.isEmpty()) {
if (isTable) {//Table自身都获取不到值,则里面的Child都无意义,不需要再解析
return response;
}
} else {
response.putAll(sqlReponse);
}
//把isTable时取出去的custom重新添加回来
if (customMap != null) {
response.putAll(customMap);
}
onFunctionResponse("0");
onChildResponse();
onFunctionResponse("+");
onComplete();
return response;
}
@Override
public void onFunctionResponse(String type) throws Exception {
Map<String, String> map = functionMap == null ? null : functionMap.get(type);
//解析函数function
Set<Entry<String, String>> functionSet = map == null ? null : map.entrySet();
if (functionSet != null && functionSet.isEmpty() == false) {
// JSONObject json = "-".equals(type) ? request : response; // key-():function 是实时执行,而不是在这里批量执行
for (Entry<String, String> entry : functionSet) {
// parseFunction(json, entry.getKey(), entry.getValue());
parseFunction(response, entry.getKey(), entry.getValue());
}
}
}
public void parseFunction(JSONObject json, String key, String value) throws Exception {
Object result;
if (key.startsWith("@")) { //TODO 以后这种小众功能从 ORM 移出,作为一个 plugin/APIJSONProcedure
FunctionBean fb = RemoteFunction.parseFunction(value, json, true);
SQLConfig config = newSQLConfig(true);
config.setProcedure(fb.toFunctionCallString(true));
result = parseResponse(config, true);
}
else {
result = parser.onFunctionParse(json, value);
}
if (result != null) {
String k = AbstractSQLConfig.getRealKey(method, key, false, false, "`"); //FIXME PG 是 "
response.put(k, result);
parser.putQueryResult(AbstractParser.getAbsPath(path, k), result);
}
}
@Override
public void onChildResponse() throws Exception {
//把isTable时取出去child解析后重新添加回来
Set<Entry<String, JSONObject>> set = childMap == null ? null : childMap.entrySet();
if (set != null) {
int index = 0;
for (Entry<String, JSONObject> entry : set) {
if (entry != null) {
response.put(entry.getKey(), onChildParse(index, entry.getKey(), entry.getValue()));
index ++;
}
}
}
}
@Override
public Object onReferenceParse(@NotNull String path) {
return parser.getValueByPath(path);
}
@Override
public JSONObject onSQLExecute() throws Exception {
JSONObject result = parser.executeSQL(sqlConfig, isSubquery);
if (isSubquery == false && result != null) {
parser.putQueryResult(path, result);//解决获取关联数据时requestObject里不存在需要的关联数据
}
return result;
}
/**
* response has the final value after parse (and query if isTable)
*/
@Override
public void onComplete() {
}
/**回收内存
*/
@Override
public void recycle() {
//后面还可能用到,要还原
if (tri) {//避免返回未传的字段
request.put(KEY_TRY, tri);
}
if (drop) {
request.put(KEY_DROP, drop);
}
method = null;
parentPath = null;
arrayConfig = null;
// if (response != null) {
// response.clear();//有效果?
// response = null;
// }
request = null;
response = null;
sqlRequest = null;
sqlReponse = null;
functionMap = null;
customMap = null;
childMap = null;
}
protected RequestMethod method;
@Override
public AbstractObjectParser setMethod(RequestMethod method) {
if (this.method != method) {
this.method = method;
sqlConfig = null;
//TODO ? sqlReponse = null;
}
return this;
}
@Override
public RequestMethod getMethod() {
return method;
}
@Override
public boolean isTable() {
return isTable;
}
@Override
public String getPath() {
return path;
}
@Override
public String getTable() {
return table;
}
@Override
public String getAlias() {
return alias;
}
@Override
public SQLConfig getArrayConfig() {
return arrayConfig;
}
@Override
public SQLConfig getSQLConfig() {
return sqlConfig;
}
@Override
public JSONObject getResponse() {
return response;
}
@Override
public JSONObject getSqlRequest() {
return sqlRequest;
}
@Override
public JSONObject getSqlReponse() {
return sqlReponse;
}
@Override
public Map<String, Object> getCustomMap() {
return customMap;
}
@Override
public Map<String, Map<String, String>> getFunctionMap() {
return functionMap;
}
@Override
public Map<String, JSONObject> getChildMap() {
return childMap;
}
}