TangCheng
2025-03-02 4960a73b581b570bd4b3aee358aaa0a8c8c0611d
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
package com.smtaiserver.smtaiserver.core;
 
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import javax.servlet.http.HttpSessionEvent;
 
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.locationtech.proj4j.CoordinateTransform;
import org.locationtech.proj4j.ProjCoordinate;
import org.mozilla.javascript.ConsString;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Undefined;
import org.mozilla.javascript.Wrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.web.context.WebApplicationContext;
 
import com.alibaba.druid.pool.DruidDataSource;
import com.smtaiserver.smtaiserver.attach.SMTAIAttachTableDef;
import com.smtaiserver.smtaiserver.database.SMTDatabase;
import com.smtaiserver.smtaiserver.gismap.SMTGisMapLayerDef;
import com.smtaiserver.smtaiserver.gismap.SMTMapOtypeDef;
import com.smtaiserver.smtaiserver.gismap.SMTMapVPropDef;
import com.smtaiserver.smtaiserver.gismap.tabledef.SMTMapTableDef;
import com.smtaiserver.smtaiserver.gismap.theme.SMTMapThemeDef;
import com.smtaiserver.smtaiserver.gismap.theme.SMTMapThemeTableDef;
import com.smtaiserver.smtaiserver.javaai.ast.ASTQuestionReplace;
import com.smtaiserver.smtaiserver.javaai.datasource.SMTDataSource;
import com.smtaiserver.smtaiserver.javaai.jsonflow.core.SMTJsonFlowManager;
import com.smtaiserver.smtaiserver.javaai.jsonflow.core.SMTJsonFlowScriptJet;
import com.smtaiserver.smtaiserver.javaai.llm.core.SMTLLMConnect;
import com.smtaiserver.smtaiserver.javaai.llm.core.SMTLLMFactory;
import com.smtaiserver.smtaiserver.javaai.metrics.base.SMTDimensionDef;
import com.smtaiserver.smtaiserver.javaai.metrics.base.SMTMetricsDef;
import com.smtaiserver.smtaiserver.javaai.querydetail.SMTAIQueryDetail;
import com.smtaiserver.smtaiserver.javaai.qwen.SMTQwenAgentManager;
import com.smtaiserver.smtaiserver.javaai.qwen.SMTQwenApp;
import com.smtaiserver.smtaiserver.javaai.sse.SMTSSEBroadcastChat;
import com.smtservlet.core.SMTApp;
import com.smtservlet.util.Json;
import com.smtservlet.util.SMTHttpClient;
import com.smtservlet.util.SMTJsonWriter;
import com.smtservlet.util.SMTStatic;
 
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
 
import com.smtservlet.core.SMTApp.SMTEhCacheManagerInitialize;
 
 
public class SMTAIServerApp extends SMTApp implements SMTEhCacheManagerInitialize,SMTApp.SMTSessionListenerEvent
{
    private static class SessionChatStreamReply
    {
        public String                        _replyId;
        public Json                            _jsonReply;
    
        public SessionChatStreamReply(String replyId, Json jsonReply)
        {
            _replyId = replyId;
            _jsonReply = jsonReply;
        }
    }
    
    
    protected Json                            _jsonSwaggerApiDoc;
    protected DruidDataSource                _dsDataSource;
    
    @Value("${hswater.logger.sql}")
    protected Boolean                        _logSQL;
    
    // 数据库连接信息,暂时和系统库一致,将来可以改成其他地方
    @Value("${spring.datasource.driver-class-name}")
    protected String                        _dbDriver;
    @Value("${spring.datasource.url}")
    protected String                        _dbUrl;
    @Value("${spring.datasource.username}")
    protected String                        _dbUser;    
    @Value("${spring.datasource.password}")
    protected String                        _dbPass;
    @Value("${spring.datasource.druid.validation-query}")
    protected String                        _dbAlidationQuery;
    @Value("${spring.datasource.druid.max-active}")
    protected int                            _dbMaxActive;
    @Value("${spring.datasource.druid.initial-size}")
    protected int                            _dbInitialSize;
    @Value("${spring.datasource.druid.min-idle}")
    protected int                            _dbMinIdle;
    @Value("${spring.datasource.druid.max-wait}")
    protected int                            _dbMaxWait;
    @Value("${spring.datasource.druid.time-between-eviction-runs-millis}")
    protected int                            _dbTimeBetweenEvictionRunsMillis;
    @Value("${spring.datasource.druid.min-evictable-idle-time-millis}")
    protected int                            _dbMinEvictableIdleTimeMillis;
    @Value("${spring.datasource.druid.test-while-idle}")
    protected boolean                        _dbTestWhileIdle;
    @Value("${spring.datasource.druid.test-on-borrow}")
    protected boolean                        _dbTestOnBorrow;
    @Value("${spring.datasource.druid.test-on-return}")
    protected boolean                        _dbTestOnReturn;
    @Value("${spring.datasource.druid.pool-prepared-statements}")
    protected boolean                        _dbPoolPreparedStatements;
    @Value("${spring.datasource.druid.max-pool-prepared-statement-per-connection-size}")
    protected int                            _dbMaxPoolPreparedStatementPerConnectionSize;
    @Value("${wiai.debug_mode}")
    protected boolean                        _isDebugMode;
    
    @Value("${wiai.table_data_source}")
    protected String                        _tableDataSource;
    
    protected SMTAIServerEncache            _serverEncache;
    
    protected Map<String, Map<String, String>>    _mapSess2AsyncProcId2Process = new HashMap<>();
    protected Map<String, SessionChatStreamReply> _mapSess2ChatStreamReply = new HashMap<>();
    protected SMTJsonFlowScriptJet            _scriptEsprima = null;
    protected Function                        _funcEsprima = null;
    protected Object                        _lockScriptEsprima = new Object();
    
    protected Map<String, SMTSSEBroadcastChat>    _mapUser2SMTSSEBroadcastChat = new HashMap<>();
 
    
    private static Pattern                    _patGroupStep = Pattern.compile("(\\d+)\\s*(minutes|hours|days|months|years|month|hour|year|day|minute)");
    private static Pattern                    _patGlobalMacro = Pattern.compile("\\{\\{\\{([\\w\\.]+)\\}\\}\\}");
    private static Logger                     _logger = LogManager.getLogger(SMTQwenApp.class);
    private static Pattern                     _patIsNumber = Pattern.compile("^[1-9]\\d*$");
    
    private static String[]                    _encacheIdList = {
        "GlobalConfig",
        "MetricsDefMap",
        "DataSourceMap",
        "DimensionMap",
        "QwenAgentManager",
        "AIQuestionReplace",
        "GISTransform",
        "queryDetailMap",
        "getLLMFactoryMap",
        "getGroupTypeMap",
        "getMapLayerDef",
        "getMapTableDefMap",
        "getMapVPropDefMap",
        "getMapThemeTableDefMap",
        "getMapThemeDefMap",
        "getAttachTableDefMap"
    };
 
    public static SMTAIServerApp getApp()
    {
        return (SMTAIServerApp)SMTApp._ThisPtr;
    }
    
    public String getDefaultLLMId() throws Exception
    {
        String defaultLLMId = System.getProperty("default_llm_id");
        if(SMTStatic.isNullOrEmpty(defaultLLMId))
            return (String)SMTAIServerApp.getApp().getGlobalConfig("llm.default.id");
        
        return defaultLLMId;
    }
    
    public String getTableDataSource()
    {
        return _tableDataSource;
    }
    
    public boolean isAppDebugMode()
    {
        return _isDebugMode;
    }
    
    public SMTSSEBroadcastChat allocBroadcastChat(String userId)
    {
        synchronized(_mapUser2SMTSSEBroadcastChat)
        {
            SMTSSEBroadcastChat chat = _mapUser2SMTSSEBroadcastChat.get(userId);
            if(chat == null)
            {
                chat = new SMTSSEBroadcastChat(userId);
                _mapUser2SMTSSEBroadcastChat.put(userId, chat);
            }
            
            return chat;
        }
    }
    
    public SMTSSEBroadcastChat getBroadcastChat(String userId)
    {
        synchronized(_mapUser2SMTSSEBroadcastChat)
        {
            SMTSSEBroadcastChat chat = _mapUser2SMTSSEBroadcastChat.get(userId);
            return chat;
        }
    }
    
    public void setServiceEncache(SMTAIServerEncache serverEncache)
    {
        _serverEncache = serverEncache;
    }
    
    public Map<String, Map<String, SMTMetricsDef>> getMetricsMapGroupMap() throws Exception
    {
        return _serverEncache.queryMetricsMapGroup();
    }
    
    public Map<String, SMTMetricsDef> getMetricsMap(String groupId) throws Exception
    {
        Map<String, Map<String, SMTMetricsDef>> mapMapMetrics = _serverEncache.queryMetricsMapGroup();
        Map<String, SMTMetricsDef> mapResult = mapMapMetrics.get(groupId);
        
        if(mapResult == null)
            throw new Exception("can't find metrics group : " + groupId);
        
        return mapResult;
    }
    
    public DruidDataSource createDruidDataSource(String driver, String dbUrl, String dbUser, String dbPass)
    {
        DruidDataSource dsDataSource = new DruidDataSource();
        dsDataSource.setDriverClassName(driver);
        dsDataSource.setUrl(dbUrl);
        dsDataSource.setUsername(dbUser);
        dsDataSource.setPassword(dbPass);
        dsDataSource.setValidationQuery(_dbAlidationQuery);
        dsDataSource.setMaxActive(_dbMaxActive);
        dsDataSource.setInitialSize(0);
        dsDataSource.setMinIdle(0);
        dsDataSource.setMaxWait(_dbMaxWait);
        dsDataSource.setTimeBetweenEvictionRunsMillis(_dbTimeBetweenEvictionRunsMillis);
        dsDataSource.setMinEvictableIdleTimeMillis(_dbMinEvictableIdleTimeMillis);
        dsDataSource.setTestWhileIdle(_dbTestWhileIdle);
        dsDataSource.setTestOnBorrow(_dbTestOnBorrow);
        dsDataSource.setTestOnReturn(_dbTestOnReturn);
        dsDataSource.setPoolPreparedStatements(_dbPoolPreparedStatements);
        dsDataSource.setMaxPoolPreparedStatementPerConnectionSize(_dbMaxPoolPreparedStatementPerConnectionSize);
        
        return dsDataSource;
    }
        
    @Override
    protected void onWebStartup(WebApplicationContext webApplicationContext) throws Exception
    {
        System.out.println("=====================================================>onWebStartup:你好");
        _logger.info("=====================================================>onWebStartup:你好");
        
        // 创建数据源
        DruidDataSource dsDataSource = new DruidDataSource();
        dsDataSource.setDriverClassName(_dbDriver);
        dsDataSource.setUrl(_dbUrl);
        dsDataSource.setUsername(_dbUser);
        dsDataSource.setPassword(_dbPass);
        dsDataSource.setValidationQuery(_dbAlidationQuery);
        dsDataSource.setMaxActive(_dbMaxActive);
        dsDataSource.setInitialSize(_dbInitialSize);
        dsDataSource.setMinIdle(_dbMinIdle);
        dsDataSource.setMaxWait(_dbMaxWait);
        dsDataSource.setTimeBetweenEvictionRunsMillis(_dbTimeBetweenEvictionRunsMillis);
        dsDataSource.setMinEvictableIdleTimeMillis(_dbMinEvictableIdleTimeMillis);
        dsDataSource.setTestWhileIdle(_dbTestWhileIdle);
        dsDataSource.setTestOnBorrow(_dbTestOnBorrow);
        dsDataSource.setTestOnReturn(_dbTestOnReturn);
        dsDataSource.setPoolPreparedStatements(_dbPoolPreparedStatements);
        dsDataSource.setMaxPoolPreparedStatementPerConnectionSize(_dbMaxPoolPreparedStatementPerConnectionSize);
        _dsDataSource = dsDataSource;
        
        
        super.onWebStartup(webApplicationContext);
        
 
        _serverEncache.getQueryDetailMap();
        _serverEncache.getLLMFactoryMap();
        _serverEncache.getMapLayerDef();
        _serverEncache.getMapTableDefMap();
        _serverEncache.getMapVPropDefMap();
        _serverEncache.getMapThemeTableDefMap();
        _serverEncache.getMapThemeDefMap();
        _serverEncache.getAttachTableDefMap();
    }
    
    public SMTMapTableDef getMapTableDef(String tableId) throws Exception
    {
        SMTMapTableDef tableDef = _serverEncache.getMapTableDefMap().get(tableId);
        if(tableDef == null)
            throw new Exception("can't find table id : " + tableId);
        return tableDef;
    }
    
    public SMTMapVPropDef getMapVPropDefMap(String OTYPE, String VPROP) throws Exception
    {
        SMTMapOtypeDef otypeDef = _serverEncache.getMapVPropDefMap().get(OTYPE);
        if(otypeDef == null)
            throw new Exception("can't get otype : " + OTYPE);
        SMTMapVPropDef vpropDef = otypeDef.getVPropDef(VPROP);
        
        return vpropDef;
    }
    
    public SMTMapOtypeDef getMapOTypeDef(String OTYPE) throws Exception
    {
        SMTMapOtypeDef otypeDef = _serverEncache.getMapVPropDefMap().get(OTYPE);
        return otypeDef;
    }
    
    public String esprimaJs2ASTStr(String code1) throws Exception
    {
        synchronized(_lockScriptEsprima)
        {
            if(_scriptEsprima == null)
            {
                // 创建esprima脚本引擎
                _scriptEsprima = new SMTJsonFlowScriptJet(); 
                Context cx = _scriptEsprima.entryContext();
                try
                {
                    InputStream is = SMTJsonFlowManager.class.getResourceAsStream("/javascript/esprima.min.js");
                    try
                    {
                        String code = SMTStatic.readTextStream(is);
                        _scriptEsprima.executeScript(cx, code);
                        
                        _funcEsprima = _scriptEsprima.compileFunction(cx, "esprimaJs2AST", "function(code){return JSON.stringify(esprima.parse(code));};");
                    }
                    finally
                    {
                        is.close();
                    }
                }
                finally
                {
                    Context.exit();
                }
 
            }
        
            Context cx = _scriptEsprima.entryContext();
            try
            {
                String strJson = (String)_scriptEsprima.callFunction(cx, _funcEsprima, new Object[] {code1});
                
                return strJson;
            }
            finally
            {
                Context.exit();
            }
        }
    }
    
    public SMTDatabase allocDatabase() throws Exception
    {
        if(_dsDataSource == null)
            return null;
        
        Connection conn = _dsDataSource.getConnection();
        
        return new SMTDatabase(conn);
    }
    
    public SMTDatabase allocNativeDatabase() throws Exception
    {    
        Connection conn = DriverManager.getConnection(_dbUrl, _dbUser, _dbPass);
        return new SMTDatabase(conn);
    }
 
 
    public boolean isLogSQL()
    {
        return (_logSQL == null) ? false : _logSQL;
    }
    
    public void readSwaggerJson(SMTJsonWriter jsonWr)
    {
        for(Entry<String, SMTRequestConfig> entry : this._mapName2RequestConfig.entrySet())
        {
            String url = "/" + entry.getKey();
            SMTRequestConfig requestConfig = entry.getValue();
            
            if(requestConfig._jsonConfig == null)
                continue;
            
            Json jsonSwaggers = requestConfig._jsonConfig.safeGetJson("swaggers");
            if(jsonSwaggers == null)
                continue;
            
            List<Json> listJsonSwagger = jsonSwaggers.asJsonList();
            if(listJsonSwagger.size() > 0)
            {
                int index = 0;
    
                Json jsonSwagger = listJsonSwagger.get(index);
                jsonWr.addKeyRaw(url, jsonSwagger);
            }
        }
    }
 
    public synchronized Json readSwaggerApiDocJson()
    {
        if(_jsonSwaggerApiDoc == null)
        {
            Set<String> setGroups = new HashSet<String>();
            SMTJsonWriter jsonWr = new SMTJsonWriter(false);
            jsonWr.addKeyValue("swagger", "2.0");
            jsonWr.beginMap("info");
            {
                jsonWr.addKeyValue("title", "Swagger操作");
                jsonWr.addKeyValue("description", "WI水务智能系统Swagger操作页面");
                jsonWr.addKeyValue("version", "1.0.0");
            }
            jsonWr.endMap();
            jsonWr.beginMap("paths");
            for(Entry<String, SMTRequestConfig> entry : this._mapName2RequestConfig.entrySet())
            {
                String url = "/" + entry.getKey();
                SMTRequestConfig requestConfig = entry.getValue();
                
                if(requestConfig._jsonConfig == null)
                    continue;
                
                Json jsonSwaggers = requestConfig._jsonConfig.safeGetJson("swaggers");
                if(jsonSwaggers == null)
                    continue;
                
                List<Json> listJsonSwagger = jsonSwaggers.asJsonList();
                int count = listJsonSwagger.size();
                for(int index = 0; index < count; index ++)
                {
                    Json jsonSwagger = listJsonSwagger.get(index);
                    jsonWr.beginMap(url + (count == 1 ? "" : String.format("?dummy=%d", index)));
                    {
                        String groupName = jsonSwagger.safeGetStr("group", null);
                        if(!SMTStatic.isNullOrEmpty(groupName))
                        {
                            jsonWr.addKeyValue("hwngroup", groupName);
                            setGroups.add(groupName);
                        }
                        
                        jsonWr.beginMap("post");
                        {
                            // 设置入参类型
                            jsonWr.beginArray("consumes");
                            jsonWr.addKeyValue(null, jsonSwagger.safeGetStr("consumes", "application/x-www-form-urlencoded"));
                            jsonWr.endArray();
                            
                            // 设置出参类型
                            jsonWr.beginArray("produces");
                            jsonWr.addKeyValue(null, "application/json");
                            jsonWr.endArray();
                            
                            // 设置返回类型
                            jsonWr.beginMap("responses");
                            {
                                jsonWr.beginMap("200");
                                {
                                    jsonWr.addKeyValue("description", "OK");
                                    jsonWr.beginMap("schema");
                                    jsonWr.addKeyValue("type", "object");
                                    Json jsonResponses = jsonSwagger.safeGetJson("responses");
                                    if(jsonResponses != null)
                                    {
                                        jsonWr.beginMap("properties");
                                        parseSwaggerRespnseJson(jsonResponses, jsonWr);
                                        jsonWr.endMap();
                                    }
                                    jsonWr.endMap();
                                }
                                jsonWr.endMap();
                            }
                            jsonWr.endMap();
                            
                            // 设置接口所属分组
                            jsonWr.addKeyRaw("tags", jsonSwagger.getJson("tags"));
                            
                            // 设置接口说明
                            jsonWr.addKeyValue("summary", jsonSwagger.getJson("title"));
                            
                            // 设置参数
                            jsonWr.beginArray("parameters");
                            
                            Json jsonParams = jsonSwagger.safeGetJson("parameters");
                            if(jsonParams != null)
                            {
                                for(Json jsonParam : jsonParams.asJsonList())
                                {
                                    jsonWr.beginMap(null);
                                    {
                                        jsonWr.addKeyValue("in", "formData");
                                        jsonWr.addKeyValue("name", jsonParam.getJson("name").asString());
                                        jsonWr.addKeyValue("description", jsonParam.getJson("title").asString());
                                        jsonWr.addKeyValue("required", jsonParam.safeGetBoolean("required", false));
                                        jsonWr.addKeyValue("type", jsonParam.safeGetStr("type", "string"));
                                        String defValue = jsonParam.safeGetStr("default", null);
                                        if(!SMTStatic.isNullOrEmpty(defValue))
                                        {
                                            jsonWr.addKeyValue("default", defValue);
                                        }
                                    }
                                    jsonWr.endMap();
                                }
                            }
                            
                            
                            jsonWr.endArray();
                            
                        }
                        jsonWr.endMap();
                    }
                    jsonWr.endMap();
                }
            }
            jsonWr.endMap();
            
            jsonWr.beginArray("hwngroups");
            for(String groupName : setGroups)
            {
                jsonWr.addKeyValue(null, groupName);
            }
            jsonWr.endArray();
 
            _jsonSwaggerApiDoc = jsonWr.getRootJson();
 
        }
        return _jsonSwaggerApiDoc;
    }
 
    private void parseSwaggerRespnseJson(Json jsonResponses, SMTJsonWriter jsonWr)
    {
        for(Json jsonResponse : jsonResponses.asJsonList())
        {
            String type = jsonResponse.safeGetStr("type", "string");
            String name = jsonResponse.getJson("name").asString();
            String title = jsonResponse.safeGetStr("title", null);
            String defValue = jsonResponse.safeGetStr("default", null);
            boolean required = jsonResponse.safeGetBoolean("required", true);
            String subType = null;
            
            if(type.endsWith("[]"))
            {
                subType = type.substring(0, type.length() - 2);
                type = "array";
            }
            
            jsonWr.beginMap(name);
            {
                jsonWr.addKeyValue("type", type);
                jsonWr.addKeyValue("required", required);
                if(!SMTStatic.isNullOrEmpty(defValue))
                    jsonWr.addKeyValue("default", title);
                if(!SMTStatic.isNullOrEmpty(title))
                    jsonWr.addKeyValue("description", title);
                
                if("array".equals(type))
                {
                    jsonWr.beginMap("items");
                    {
                        jsonWr.addKeyValue("type", subType);
                        if("object".equals(subType))
                        {
                            jsonWr.beginMap("properties");
                            parseSwaggerRespnseJson(jsonResponse.getJson("children"), jsonWr);
                            jsonWr.endMap();
                        }
                    }
                    jsonWr.endMap();
                }
                else if("object".equals(type))
                {
                    jsonWr.beginMap("properties");
                    parseSwaggerRespnseJson(jsonResponse.getJson("children"), jsonWr);
                    jsonWr.endMap();
                }
            }
            jsonWr.endMap();
        }
    }
 
    @Override
    public void initEhCacheManager(CacheManager cacheManager)
    {
        for(String encacheId : _encacheIdList)
        {
            cacheManager.addCache(new Cache(encacheId, 1000, false, true, 100, 100));
        }
        
    }
 
    @Override
    public void clearEhCacheManager(CacheManager cacheManager)
    {
        for(String encacheId : _encacheIdList)
        {
            cacheManager.getCache(encacheId).removeAll();
        }
    }
 
    public Object getGlobalConfig(String key, Object defValue) throws Exception
    {
        Map<String, Object> map = _serverEncache.queryGlobalConfigMap();
        Object value = map.get(key);
        if(value == null)
            return defValue;
 
        return value;
    }
    
    public Object getGlobalConfig(String key) throws Exception
    {
        Object value = getGlobalConfig(key, null);
        if(value == null)
            throw new Exception("can't find global key : " + key);
 
        return value;
    }
    
    public Json queryAIPythonServer(String url, SMTJsonWriter jsonWr) throws Exception
    {
        String urlRoot = (String) getGlobalConfig("aipython.url");
        SMTHttpClient web = new SMTHttpClient();
        return web.postHttpBodyToJson(urlRoot + url, jsonWr.getFullJson(), null);
    }
    
    public String createQuestionSession(SMTDatabase db, String question, SMTJsonWriter jsonResult) throws Exception
    {
        String sessionId = SMTStatic.newUUID();
        db.executeSQL(
            "INSERT INTO ai_question_session(session_id, create_time, question, result_json)VALUES(?, ?, ?, ?)", new Object[] {
                sessionId,
                new Date(),
                question,
                jsonResult.getFullJson()
            });
        
        return sessionId;
    }
 
    @Override
    public void sessionCreated(HttpSessionEvent event) throws Exception
    {
        synchronized(_mapSess2AsyncProcId2Process)
        {
            _mapSess2AsyncProcId2Process.put(event.getSession().getId(), new HashMap<>());
        }
 
    }
 
    @Override
    public void sessionDestroyed(HttpSessionEvent event) throws Exception
    {
        String sessionId = event.getSession().getId();
        
        synchronized(_mapSess2AsyncProcId2Process)
        {
            _mapSess2AsyncProcId2Process.remove(sessionId);
        }
        
        synchronized(_mapSess2ChatStreamReply)
        {
            _mapSess2ChatStreamReply.remove(sessionId);
        }        
        
        synchronized(_mapUser2SMTSSEBroadcastChat)
        {
            // 因为不知道所属用户,所以需要扫描一下用户
            for(SMTSSEBroadcastChat chat : _mapUser2SMTSSEBroadcastChat.values())
            {
                if(chat.removeSSEConnect(sessionId))
                    break;
            }
        }
    }
    
    public void clearChatStreamReply(String sessionId)
    {
        synchronized(_mapSess2ChatStreamReply)
        {
            _mapSess2ChatStreamReply.remove(sessionId);
        }
    }
    
    public void setChatStreamReply(String sessionId, String replyId, Json jsonReply)
    {
        synchronized(_mapSess2ChatStreamReply)
        {
            _mapSess2ChatStreamReply.put(sessionId, new SessionChatStreamReply(replyId, jsonReply));
        }        
    }
    
    public Json getChatStreamReply(String sessionId, String replyId)
    {
        SessionChatStreamReply reply = null;
        synchronized(_mapSess2ChatStreamReply)
        {
            reply = _mapSess2ChatStreamReply.get(sessionId);
            if(reply == null || !reply._replyId.equals(replyId))
                return null;
            
            return     reply._jsonReply;
        }        
        
 
    }
    
    public void removeAsyncProcessText(String sessionId, String processId)
    {
        synchronized(_mapSess2AsyncProcId2Process)
        {
            Map<String, String> mapId2Process = _mapSess2AsyncProcId2Process.get(sessionId);
            if(mapId2Process == null)
                return;
            mapId2Process.remove(processId);
        }
    }
    
    public void setAsyncProcessText(String sessionId, String processId, String text)
    {
        synchronized(_mapSess2AsyncProcId2Process)
        {
            Map<String, String> mapId2Process = _mapSess2AsyncProcId2Process.get(sessionId);
            if(mapId2Process == null)
                return;
            mapId2Process.put(processId, text);
        }
    }
    
    public String getAsyncProcessText(String sessionId, String processId)
    {
        synchronized(_mapSess2AsyncProcId2Process)
        {
            Map<String, String> mapId2Process = _mapSess2AsyncProcId2Process.get(sessionId);
            if(mapId2Process == null)
                return null;
            
            return mapId2Process.get(processId);
            
        }
    }
    
    public Map<String, SMTDataSource> getDataSourceMap() throws Exception
    {
        return _serverEncache.queryDataSourceMap();
    }
    
    public SMTDataSource getDataSource(String id) throws Exception
    {
        Map<String, SMTDataSource> map = getDataSourceMap();
        SMTDataSource result = map.get(id);
        if(result == null)
            throw new Exception("data source is not exist : " + id);
        
        return result;
    }
    
    public SMTDimensionDef    getDimensionDef(String id) throws Exception
    {
        Map<String, SMTDimensionDef> map = _serverEncache.queryDimensionMap();
        SMTDimensionDef dimDef = map.get(id);
        if(dimDef == null)
            throw new Exception("can't find dimension def : " + id);
        
        return dimDef;
    }
    
    public Map<String, SMTDimensionDef> getDimensionDefMap() throws Exception
    {
        return _serverEncache.queryDimensionMap();
    }
    
    public String convGlobalMacroString(String str, Json jsonExtMacro) throws Exception
    {
        while(true)
        {
            boolean hasMatcher = false;
            Matcher m = _patGlobalMacro.matcher(str);
            String newStr = str;
            while(m.find())
            {
                hasMatcher = true;
                
                String newValue = null;
                
                if(jsonExtMacro != null)
                    newValue = jsonExtMacro.safeGetStr(m.group(1), null);
                if(newValue != null)
                {
                    newStr = str.replace(m.group(), newValue);
                }
                else
                {
                    newStr = str.replace(m.group(), (String)this.getGlobalConfig(m.group(1)));
                }
            }
            str = newStr;
            if(!hasMatcher)
                return newStr;
        }
 
    }
    
    public static String formatXmlToNoRootStr(Document doc) throws Exception
    {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        format.setNewLineAfterDeclaration(false);
        format.setNewlines(true);
        format.setTrimText(false);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        XMLWriter writer= new XMLWriter(bos,format);
        writer.setEscapeText(true);
 
        writer.write(doc);
        writer.close();
        String str = bos.toString("UTF-8");
        
        int posS = str.indexOf("<ROOT>");
        if(posS < 0)
            throw new Exception("can't find <ROOT>");
        int posE = str.lastIndexOf("</ROOT>");
        if(posE < 0)
            throw new Exception("can't find </ROOT>");    
        
        String[] lines = str.substring(posS + 6, posE).replace("\r\n", "\n").split("\n");
        StringBuilder sb = new StringBuilder();
        for(String line : lines)
        {
            if(line.trim().length() == 0)
                continue;
            sb.append(line + "\n");
        }
        
        return sb.toString();
    }
    
    public SMTQwenAgentManager getQwenAgentManager() throws Exception
    {
        return this._serverEncache.getQwenAgentManager();
    }
    
    public int getOutputAITableMax() throws Exception
    {
        return SMTStatic.toInt(getGlobalConfig("ai_table_output.max_rows", "100"));
    }
    
    public void clearQwenAgentManager() throws Exception
    {
        EhCacheCacheManager springCacheManager = SMTApp.getBean(EhCacheCacheManager.class);
        if(springCacheManager != null)
        {
            CacheManager cacheManager = springCacheManager.getCacheManager();
            cacheManager.getCache("QwenAgentManager").removeAll();
        }
    }
    
    public static String convTimeStepToUnitStr(int unit, int value)
    {
        if(unit == 0)
        {
            int deltaDay = 24 * 60;
            if((value % deltaDay) == 0)
                return SMTStatic.toString(value / deltaDay) + " days";
            
            if((value % 60) == 0)
                return SMTStatic.toString(value / 60) + " hours";
            
            return SMTStatic.toString(value) + " minutes";
        }
        else
        {
            if((value % 12) == 0)
                return SMTStatic.toString(value / 12) + " years";
            
            return SMTStatic.toString(value) + " months";
        }
        
    }
    
    public static String convTimeStepToStr(int unit, int value)
    {
        if(unit == 0)
        {
            int deltaDay = 24 * 60;
            if((value % deltaDay) == 0)
                return SMTStatic.toString(value / deltaDay) + "天";
            
            if((value % 60) == 0)
                return SMTStatic.toString(value / 60) + "时";
            
            return SMTStatic.toString(value) + "分";
        }
        else
        {
            if((value % 12) == 0)
                return SMTStatic.toString(value / 12) + "年";
            
            return SMTStatic.toString(value) + "月";
        }
        
    }
    
    public static int[] convStrToTimeStep(String sTimeStep)
    {
        int _timeStepUnit = 0;
        int  _timeStepValue = 0;
        
        Matcher m = _patGroupStep.matcher(sTimeStep);
        if(!m.find())
            return null;
        
        int groupStep = SMTStatic.toInt(m.group(1));
        String sGroupUnit = m.group(2);
        if("minutes".equals(sGroupUnit))
        {
            _timeStepUnit = 0;
            _timeStepValue = groupStep;
        }
        else if("hours".equals(sGroupUnit) || "hour".equals(sGroupUnit))
        {
            _timeStepUnit = 0;
            _timeStepValue = groupStep * 60;
        }
        else if("days".equals(sGroupUnit) || "day".equals(sGroupUnit))
        {
            _timeStepUnit = 0;
            _timeStepValue = groupStep * 60 * 24;
        }
        else if("months".equals(sGroupUnit) || "month".equals(sGroupUnit))
        {
            _timeStepUnit = 1;
            _timeStepValue = groupStep;
        }
        else if("years".equals(sGroupUnit) || "year".equals(sGroupUnit))
        {
            _timeStepUnit = 1;
            _timeStepValue = groupStep * 12;
        }    
        
        return new int[] {_timeStepUnit, _timeStepValue};
    }
    
    public ASTQuestionReplace getQueryAIQuestionReplace() throws Exception
    {
        return _serverEncache.getQueryAIQuestionReplace();
    }
    
    public double[] convMapToGisTransform(double[] pos) throws Exception
    {
        CoordinateTransform[] transforms = _serverEncache.getGisTransform();
        
        double[] result = new double[pos.length];
        for(int i = 0; i < pos.length; i += 2)
        {
            ProjCoordinate sourceCoord = new ProjCoordinate(pos[i + 0], pos[i + 1]);
            ProjCoordinate targetCoord = new ProjCoordinate();
            transforms[1].transform(sourceCoord, targetCoord);
            result[i + 0] = targetCoord.x;
            result[i + 1] = targetCoord.y;
        }
        
        return result;
    }
    
    public double[] convGisToMapTransform(double[] pos) throws Exception
    {
        CoordinateTransform[] transforms = _serverEncache.getGisTransform();
        
        double[] result = new double[pos.length];
        for(int i = 0; i < pos.length; i += 2)
        {
            ProjCoordinate sourceCoord = new ProjCoordinate(pos[i + 0], pos[i + 1]);
            ProjCoordinate targetCoord = new ProjCoordinate();
            transforms[0].transform(sourceCoord, targetCoord);
            result[i + 0] = targetCoord.x;
            result[i + 1] = targetCoord.y;
        }
        
        return result;
    }
    
    public SMTAIQueryDetail getQueryDetail(String id) throws Exception
    {
        SMTAIQueryDetail queryDetail = _serverEncache.getQueryDetailMap().get(id);
        if(queryDetail == null)
            throw new Exception("can't find query detail id : " + id);
        
        return queryDetail;
    }
    
    public static Object unwrapObject(Object value)
    {
        if(value == null)
            return null;
        
        if(value instanceof Wrapper)
            value = ((Wrapper)value).unwrap();
        
        if(value instanceof Undefined)
            return null;
        
        if(value instanceof ConsString)
            value = ((ConsString)value).toString();
            
        return value;
    }
    
    public static void convJSToJsonWriter(Object jsObject, SMTJsonWriter jsonWr)
    {
        if(jsObject instanceof NativeObject)
        {
            NativeObject nvObject = (NativeObject)jsObject;
            for(Entry<Object, Object> entry : nvObject.entrySet())
            {
                String key = SMTStatic.toString(unwrapObject(entry.getKey()));
                putJSToJsonWriter(jsonWr, key, entry.getValue());
            }
        }
        else if(jsObject instanceof NativeArray)
        {
            NativeArray arrObject =(NativeArray)jsObject;
            for(int i = 0; i < arrObject.size(); i ++)
            {
                putJSToJsonWriter(jsonWr, null, arrObject.get(i));
            }
        }
    }
    
    public static void putJSToJsonWriter(SMTJsonWriter jsonWr, String jsonKey, Object jsObject)
    {
        if(jsObject instanceof NativeObject)
        {
            NativeObject nvObject = (NativeObject)jsObject;
            jsonWr.beginMap(jsonKey);
            for(Entry<Object, Object> entry : nvObject.entrySet())
            {
                String key = SMTStatic.toString(unwrapObject(entry.getKey()));
                putJSToJsonWriter(jsonWr, key, entry.getValue());
            }
            jsonWr.endMap();
        }
        else if(jsObject instanceof NativeArray)
        {
            NativeArray arrObject =(NativeArray)jsObject;
            jsonWr.beginArray(jsonKey);
            for(int i = 0; i < arrObject.size(); i ++)
            {
                putJSToJsonWriter(jsonWr, null, arrObject.get(i));
            }
            jsonWr.endArray();
        }
        else
        {
            jsonWr.addKeyValue(jsonKey, unwrapObject(jsObject));
        }
    }
    
    public static Object convJsonToJS(Json json)
    {
        if(json.isObject())
        {
            NativeObject nv = new NativeObject();
            for(Entry<String, Json> entry : json.asJsonMap().entrySet())
            {
                putJSNotNullValue(nv, entry.getKey(), convJsonToJS(entry.getValue()));
            }
            return nv;
        }
        else if(json.isArray())
        {
            List<Object> list = new ArrayList<Object>();
            for(Json subJson : json.asJsonList())
            {
                list.add(convJsonToJS(subJson));
            }
            
            return new NativeArray(list.toArray(new Object[list.size()]));
        }
        else if(json.isNull())
            return null;
        else
            return json.getValue();
    }
    
    public static void putJSNotNullValue(NativeObject nv, String key, Object value)
    {
        if(value == null)
            return;
        if(_patIsNumber.matcher(key).find())
            nv.put(Integer.parseInt(key), nv, value);
        else
            nv.put(key, nv, value);
    }
    
    public static Object getJSValue(NativeObject nv, String key) throws Exception
    {
        if(!nv.containsKey(key))
            throw new Exception("NativeObject can't find key : " + key);
        Object value = unwrapObject(nv.get(key));
        if(value == null)
            throw new Exception("NativeObject can't find key : " + key);
        return value;
    }
    
    public static Object getJSValue(NativeObject nv, String key, Object defValue) throws Exception
    {
        Object okey;
        if(_patIsNumber.matcher(key).find())
            okey = Long.parseLong(key);
        else
            okey = key;
        if(!nv.containsKey(okey))
            return defValue;
        Object value = unwrapObject(nv.get(okey));
        if(value == null)
            return defValue;
        
        return value;
    }
 
    public SMTLLMConnect allocLLMConnect(String llmId) throws Exception
    {
        if(SMTStatic.isNullOrEmpty(llmId))
            llmId = (String) getDefaultLLMId();
        
        Map<String, SMTLLMFactory> map = _serverEncache.getLLMFactoryMap();
        SMTLLMFactory factory = map.get(llmId);
        if(factory == null)
            throw new Exception("can't find llm factory : " + llmId);
        
        return factory.allocLLM();
    }
    
    public String getGroupTypeByGroupId(String groupId) throws Exception
    {
        String groupType = _serverEncache.getGroupTypeMap().get(groupId);
        if(groupType == null)
            throw new Exception("can't find group id : " + groupId);
        
        return groupType;
    }
    
    public SMTGisMapLayerDef getMapLayerDef(String layerId) throws Exception
    {
        SMTGisMapLayerDef mapLayerDef = _serverEncache.getMapLayerDef().get(layerId);
        if(mapLayerDef == null)
            throw new Exception("can't find layer id : " + layerId);
        
        return mapLayerDef;
    }
    
    public Map<String, SMTGisMapLayerDef> getMapLayerDefMap() throws Exception
    {
        Map<String, SMTGisMapLayerDef> map = _serverEncache.getMapLayerDef();
        
        return map;
    }
    
    public Map<String, SMTMapOtypeDef>    getMapVPropDefMap() throws Exception
    {
        Map<String, SMTMapOtypeDef> map = _serverEncache.getMapVPropDefMap();
        
        return map;
    }
    
    public SMTMapThemeTableDef    getMapThemeTableDefMap(String id) throws Exception
    {
        SMTMapThemeTableDef themeTableDef = _serverEncache.getMapThemeTableDefMap().get(id);
        if(themeTableDef == null)
            throw new Exception("can't find theme table : " + id);
        
        return themeTableDef;
    }
    
    public Map<String, SMTMapThemeDef>    getMapThemeDefMap() throws Exception
    {
        return _serverEncache.getMapThemeDefMap();
    }
    
    public SMTMapThemeTableDef getMapThemeTableDef(String id) throws Exception
    {
        SMTMapThemeTableDef themeTableDef = _serverEncache.getMapThemeTableDefMap().get(id);
        if(themeTableDef == null)
            throw new Exception("can't find theme table define : " + id);
        
        return themeTableDef;
    }
    
    public SMTMapThemeDef getMapThemeDef(String id) throws Exception
    {
        SMTMapThemeDef themeDef = _serverEncache.getMapThemeDefMap().get(id);
        if(themeDef == null)
            throw new Exception("can't find theme def : " + id);
        
        return themeDef;
    }
    
    public Map<String, SMTAIAttachTableDef> getAttachTableDefMap() throws Exception
    {
        return _serverEncache.getAttachTableDefMap();
    }
    
    public SMTAIAttachTableDef getAttachTableDef(String id) throws Exception
    {
        SMTAIAttachTableDef attachTableDef = _serverEncache.getAttachTableDefMap().get(id);
        if(attachTableDef == null)
            throw new Exception("can't find attach table define : " + id);
        
        return attachTableDef;
    }
}