fs-danaus
2023-07-10 4849078e3450b8d3b3030a658a34dd58b0630fc5
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
package com.yc.action.panval;
 
import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.yc.action.BaseAction;
import com.yc.entity.DataSourceActionEntity;
import com.yc.entity.DataSourceActionEntity.ActionEnum;
import com.yc.entity.DataSourceEntity;
import com.yc.entity.DemoConstant;
import com.yc.exception.ApplicationException;
import com.yc.exception.CallBackMessage;
import com.yc.factory.FactoryBean;
import com.yc.multiData.JdbcPoolConfig;
import com.yc.multiData.MultiDataSource;
import com.yc.multiData.SpObserver;
import com.yc.sdk.WebSocketMessage.action.WebSocketMessageServer;
import com.yc.sdk.WebSocketMessage.entity.MessageInfo;
import com.yc.sdk.WebSocketMessage.entity.MessageType;
import com.yc.sdk.password.action.ChangePassword;
import com.yc.sdk.shopping.util.SettingKey;
import com.yc.sdk.weixincp.util.AsynchronousExecution;
import com.yc.service.BaseService;
import com.yc.service.demo.DemoIfc;
import com.yc.service.grid.GridServiceIfc;
import com.yc.service.impl.DBHelper;
import com.yc.service.impl.EnvHelper;
import com.yc.service.oapanel.WebMenuAccessIfc;
import com.yc.service.panel.*;
import com.yc.service.panel.v2.PanelBean;
import com.yc.service.panel.v2.TypeControl;
import com.yc.service.panel.v2.TypeControlDao;
import com.yc.utils.EncodeUtil;
import com.yc.utils.SessionKey;
import com.yc.utils.fileAndFolder.FileAndFolderOper;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Catalina;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
 
import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.Raster;
import java.io.*;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
//import peng.pb.io.FileDo;
 
@Controller
public class InvGet extends BaseAction {
    @Autowired
    PanelValueDao pDao;
    @Autowired
    SystemSettingsDao sysDao;
    @Autowired
    WebMenuAccessIfc wIfc;
    @Autowired
    TypeControlDao tControlDao;
    @Autowired
    SqlDBHelperIfc sqlDBHelperIfc;
    @Autowired
    DemoIfc demoIfc;
    @Autowired
    DemoIfc dIfc;
    @Autowired
    DiBangIfc diBangIfc;
    @Autowired
    GridServiceIfc gridServiceIfc;
    //@Autowired
    //private DefaultLobHandler defaultLobHandler;
    private final Catalina EMBEDDED = new Catalina();
    private  final Logger log = LoggerFactory.getLogger(this.getClass());
    public FileAndFolderOper FAFO = new FileAndFolderOper();
    public static String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    public static Integer initialPoolSize = Integer.parseInt(JdbcPoolConfig.get("cop3.initialPoolSize")); //5 ;
    public static Integer minPoolSize = Integer.parseInt(JdbcPoolConfig.get("cop3.minPoolSize"));//5 ;
    public static Integer maxPoolSize = Integer.parseInt(JdbcPoolConfig.get("cop3.maxPoolSize"));//50 ;
    public static Integer acquireIncrement =Integer.parseInt(JdbcPoolConfig.get("cop3.acquireIncrement"));// 5 ;
    public static Integer maxIdleTime = Integer.parseInt(JdbcPoolConfig.get("cop3.maxIdleTime"));//1800 ;
    public static Integer idleConnectionTestPeriod = Integer.parseInt(JdbcPoolConfig.get("cop3.idleConnectionTestPeriod"));//1800 ;
    public static Integer maxStatements = Integer.parseInt(JdbcPoolConfig.get("cop3.maxStatements"));//0 ;
 
 
    @RequestMapping("/inv.do")
    public void login(int id, String where, String sel, String get, HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        try {
            where = URLDecoder.decode(where, "utf-8");
            SpObserver.setDBtoInstance("_"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            if (!sel.equals("") && id > -1) {// 这为2类型下拉,控制下吧,
                this.print(response, pDao.getStr(id, where, sel, get));
            } else {
                this.print(response, "");
            }
        } catch (Exception e) {
            this.print(response, e.getCause()!=null?e.getCause().getMessage():e.getMessage());
        }finally {
            SpObserver.setDBtoInstance();
        }        
        
    }
 
    @RequestMapping("/invAll.do")
    public void login(int id, String where, HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        try {
            where = URLDecoder.decode(where, "utf-8");
            SpObserver.setDBtoInstance("_"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            if (id < 0) {
                this.print(response, "");
            } else {
                this.print(response,pDao.getStrAll(id, where));
            }
        } catch (Exception e) {
            this.print(response, e.getCause()!=null?e.getCause().getMessage():e.getMessage());
        }finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    @RequestMapping("/invAlldiv.do")
    public void login(int id, String where, String sugg, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            where = URLDecoder.decode(where, "utf-8");
            SpObserver.setDBtoInstance("_"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            if (id < 0) {
                this.print(response, "");
            } else {
                where = getwherezdy(where, request);
                this.print(response,pDao.getStrAll42(id, where, "42", sugg));
            }
        } catch (Exception e) {
            this.print(response, e.getCause()!=null?e.getCause().getMessage():e.getMessage());
        }finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 针对面板的42控件取值的方法 xin 2021-3-18 14:01:33
     * 这个方法是新的,且是面板42控件调用,旧方法是上面的/invAlldiv.do
     * @param request
     * @param response
     */
    @RequestMapping("/panelControlData42.do")
    public void getPanelControlData42(int page,int limit,int ft,String where,String sugg,int formType,String parameter,
                                      HttpServletRequest request,HttpServletResponse response) {
        try {
            SpObserver.setDBtoInstance("_" + request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            if (ft <= 0) {//表号为空
                super.printJson(response, "");
                return;
            }
            where = URLDecoder.decode(where, "utf-8");
            where = getwherezdy(where, request);
            String value = pDao.getStrAll42(page, limit, ft, where, sugg,formType,parameter);
            super.printJson(response, value);
        } catch (Exception e) {
         super.printJson(response,new CallBackMessage().sendErrorMessage(e.getCause()!=null?e.getCause().getMessage():e.getMessage()));
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    /**
     * 处理@符号替换
     * @param where处理的条件
     * @param request
     * @return
     */
    public String getwherezdy(String where, HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            if ((where.indexOf("@~")) != -1) {
                where = where.replaceAll("@~", "%");
            }
            // if(where.indexOf("'@'"))
            if ((where.indexOf("@")) != -1) {
                while ((where.indexOf("@")) != -1) {
                    String tes = "";
                    Pattern ps = Pattern.compile("@.*?\\w+");// 匹配以@开头的单词
                    Matcher propsMatchers = ps.matcher(where);
                    while (propsMatchers.find()) {
                        tes = propsMatchers.group();
                    }
                    String se = session.getAttribute(tes.toLowerCase()) == null ? tes : session.getAttribute(tes.toLowerCase()).toString();//
 
                    where = where.replaceAll(tes, se);
 
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return where;
    }
 
    @RequestMapping("/NeedWork.do")
    public void NeedWork(String UNID, String actionType,int formId, String doccode, int formType, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            SpObserver.setDBtoInstance("_"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            wIfc.setIsRead(UNID);
            HttpSession session = request.getSession();
            String url = SettingKey.getHostUrl(request) +
                    "/app/" + session.getAttribute(SessionKey.DATA_BASE_ID) + "/" + session.getAttribute(SessionKey.VERSION_ID) + "/" + session.getAttribute(SessionKey.SYSTEM_LANGUAGE)
 
                    + "/" + formId + "/" + formType + "/index.jsp?" + EncodeUtil.base64Encode("isNew=ie&doccode=\'" + doccode + "\'");
            response.sendRedirect(url);
        }catch (Exception e) {
            this.print(response, e.getCause()!=null?e.getCause().getMessage():e.getMessage());
        }finally {
            SpObserver.setDBtoInstance();
        }
    }
    @RequestMapping("/NeedWorkOK.do")
    public void NeedWorkOk(String UNID,String actionType, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            SpObserver.setDBtoInstance("_"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
            this.print(response, wIfc.setIsRead(UNID)+"");
        }catch (Exception e) {
            this.print(response, e.getCause()!=null?e.getCause().getMessage():e.getMessage());
        }finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    @RequestMapping("/getDiBang.do")
    public void getDiBang(String ip, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        // Map<String, Object> oMap = diBangIfc.getDiBangInfo(ip);
        String hostname = request.getParameter("hostname");
        try {
            SpObserver.setDBtoInstance("_"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
        Map<String, Object> oMap = diBangIfc.getDiBangInfo(ip, hostname);
        session.setAttribute(SessionKey.IP_ADDRESS, ip);// 赋地磅信息session值
        session.setAttribute(SessionKey.HOSTNAME, hostname);
        session.setAttribute(SessionKey.MAC_ADDRESS, request.getParameter("MacAddress"));
        String loadername = "";
        if (oMap != null && !oMap.isEmpty()) {
            out.print("hasParm:1,");
            out.print("isrndstart:" + DBHelper.getValue(oMap, "isRndStart") + ",");
            out.print("decimals:" + DBHelper.getValueInt(oMap, "Decimals") + ","); // 小数位数: 1 表示1个小数位,2,表示2个小数位
            out.print("eloadprebits:" + DBHelper.getValueInt(oMap, "EloadPrebits") + ","); // 从第1个字符开始丢弃的字符个数
            out.print("eloadbits:" + DBHelper.getValueInt(oMap, "Eloadbits") + ","); // 连续取字符串长度
            out.print("bufferlength:" + DBHelper.getValueInt(oMap, "BufferLength") + ","); // 缓冲区长度
            out.print("newlinesepchar:" + DBHelper.getValueInt(oMap, "NewLineSepChar") + ","); // 换行分隔符
            out.print("enterkeysepchar:" + DBHelper.getValueInt(oMap, "EnterkeySepChar") + ","); // 回车分隔符
            out.print("othersepchar:" + DBHelper.getValue(oMap, "OtherSepChar") + ","); // 其它分隔符
            out.print("isreservchar:" + DBHelper.getValueInt(oMap, "IsReservChar") + ","); // 是否反转显示字符串
            out.print("portnum:" + DBHelper.getValueInt(oMap, "LoadPort") + ","); // 端口号 , 1 表示 com1 , 2 表示 com1 以此类推
            out.print("bandrate:" + DBHelper.getValueInt(oMap, "BandRate") + ","); // 设置波特率 , 缺省 2400
            out.print("databit:" + DBHelper.getValueInt(oMap, "DataBit") + ","); // 数据位 , 缺省 8
            out.print("parity:" + DBHelper.getValue(oMap, "CRCbit") + ","); // 奇偶校验 , n 表示NONE 无
            out.print("stopbit:" + DBHelper.getValueInt(oMap, "StopBit") + ","); // 停止位 ,缺省 1
            out.print("isdebug:" + DBHelper.getValueInt(oMap, "isDebug") + ""); // 是否为调试
            loadername = DBHelper.getValue(oMap, "LoaderName");
        } else {
            out.print("hasParm:0");
        }
        session.setAttribute(SessionKey.LOADER_NAME, loadername);
        out.flush();
        out.close();
        }catch (Exception e) {
            this.print(response, e.getCause()!=null?e.getCause().getMessage():e.getMessage());
        }finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    @RequestMapping("/getDoc.do")
    public void getDoc(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String doccode = request.getParameter("doccode");
        String t_doc = request.getParameter("t_doc");
        String tUrl = request.getParameter("tUrl");
        String[] tStrings = tUrl.split("\\?");
        tStrings[1] = EncodeUtil.base64Encode(EncodeUtil.base64Decode(tStrings[1]).replace(doccode, t_doc));
        this.print(response,tStrings[0] + "?" + tStrings[1]);
    }
 
    @RequestMapping("/getDateDemo.do")
    public void getData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String path = request.getServletContext().getRealPath("/");
        EnvHelper.setPath(path);// 得到项目的地址,方便后面使用
        String text = request.getParameter("dataBaseDis");
        String str_version = request.getParameter("version");
        String id = request.getParameter("id");
        HttpSession session = request.getSession();
        if (id != null) {
            Cookie cookie = new Cookie("selectDatabase", id);
            cookie.setMaxAge(604800);// 保存一周60×60×20×7
            response.addCookie(cookie);
            // System.out.println("选择配置文件为_" + id + ".xml");
            session.setAttribute(SessionKey.DATA_BASE_ID, id);
            session.setAttribute("databaseDis", text == null ? "" : text);
            session.setAttribute("indexSelected", id);
        }
        int version = 0;
        try {
            version = Integer.parseInt(str_version);
        } catch (Exception e) {
        }
        session.setAttribute(SessionKey.VERSION_ID, version);
        // SpObserver.setDBtoInstance("_" + id);// 确立选择的配置文件
    }
 
    @RequestMapping("/SyncDataSource.do")
    public void syncDataSource(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            String dbId = request.getParameter(SessionKey.DATA_BASE_ID) ;  //从URL读取 dbid 参数
            //String isDeleted = request.getParameter(SessionKey.isDeleted) ;  //是否正在删除
            refreshDataSource(dbId,DataSourceActionEntity.ActionEnum.REFRESH);
            this.print(response, "同步更新集群主机的数据源成功!");
            System.out.println("同步更新集群主机的数据源成功!");
        }catch (Exception e) {
            this.print(response, e.getMessage());
        }
    }
 
    public static boolean refreshDataSource(String dbId,ActionEnum action) throws Exception{
        DataSourceEntity oldDataSource=null;
        DataSourceEntity newDataSource=null;
        if (dbId!=null) {
            MultiDataSource multiDataSource = (MultiDataSource) FactoryBean.getBean("multiDataSource");
             oldDataSource = MultiDataSource.getDataSourceMap(dbId);//取内存数据
            List<DataSourceEntity> newSourceList = multiDataSource.refreshDataSource(dbId);// 是为了增加一个数据源实现不重启就可以访问新增的数据源。也就是对原有保存在内存的数据源集合进行更新 2014-11-26
            if(newSourceList!=null&&newSourceList.size()>0) {
                MultiDataSource.getDataSourceMaps().put(dbId, newSourceList.get(0));
                newDataSource = MultiDataSource.getDataSourceMap(dbId);
            }else {
                throw new ApplicationException("获取新数据源出错:"+dbId);
            }
 
        }
        MessageInfo messageInfo = new MessageInfo();
        //---刷新本地tomcat内存的数据源
        messageInfo.setMsgType(MessageType.CHECK_SYSTEM_DISABLED);
        messageInfo.setDbId(dbId==null?null:Integer.parseInt(dbId));
        DataSourceActionEntity dataSourceActionEntity = new DataSourceActionEntity() ;
        dataSourceActionEntity.setDbId(dbId);
        dataSourceActionEntity.setAction(action.getName());
        messageInfo.setMsg(JSON.toJSONString(dataSourceActionEntity));
        WebSocketMessageServer.publishMessageToRedis(messageInfo);
        //---webscoket通知web端和APP端
        if(oldDataSource!=null&&newDataSource!=null) {
 
            String actionType=null;
            if(oldDataSource.isExpiredDate()&&!newDataSource.isExpiredDate())
            {
                actionType="start";
            }
            if(!oldDataSource.isExpiredDate()&&newDataSource.isExpiredDate())
            {
                actionType="stop";
            }
            if(actionType!=null&&!"".equals(actionType)) {
                MessageInfo info = new MessageInfo();
                info.setDbId(Integer.parseInt(dbId));
                if ("stop".equalsIgnoreCase(actionType)) {
                    info.setMsgType(MessageType.NOTICE_SYSTEM_STOP);
                } else {
                    info.setMsgType(MessageType.NOTICE_SYSTEM_START);
                    //info.setUserFromType("1");//作为key的一部分,识别是用来刷新登录页面
                }
                WebSocketMessageServer.publishMessageToRedis(info);
            }
        }
        return true ;
    }
 
    /**
     * 判断当前 dbid 是否存在于 cookies 中
     * @param request
     * @param dbId
     * @return
     */
    public static boolean isExistsDatabaseIdByCookie(HttpServletRequest request,String dbId) {
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for(int i=0;i<cookies.length;i++){
                if(cookies[i].getName().equals("selectDatabase") && !"".equals(dbId) && dbId.equals(cookies[i].getValue())){
                    return true ;
                }
            }
        }
        return false ;
    }
 
    @RequestMapping("/getInvitationCode.do")
    public void getInvitationCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            SpObserver.setDBtoDemo();
            String invitationCode =dIfc.getInvitationCode() ;
            this.print(response, invitationCode);
        }catch (DataAccessException e) {
            e.printStackTrace();
            this.print(response,"修改出错!错误原因:" + (e.getCause()!=null? e.getCause().getMessage():e.getMessage()));
            return ;
        } catch (Exception e) {
            e.printStackTrace();
            this.print(response,"修改出错!错误原因:" + (e.getCause()!=null? e.getCause().getMessage():e.getMessage()));
            return ;
        }finally {
            SpObserver.setDBtoInstance();
        }
    }
 
//    @RequestMapping("/saveSystemConfig.do") //修改人 xin 2021-1-18 11:02:47
    private void saveSystemConfig(MultipartFile logoFile,DataSourceEntity dataSourceEntity,HttpServletRequest request, HttpServletResponse response) throws Exception {
        JsonObject json = new JsonObject();
        JsonObject errJson = new JsonObject();
//        String logodel = request.getParameter("logodel");//logo删除 ,1表示删除 0不处理  xin 2019-11-9 16:45:38
        //String hostUrl = SettingKey.getHostUrl(request) ;
        try {
            SpObserver.setDBtoDemo();
//            DataSourceEntity dataSourceEntity = getConnMap(request,response, "");
//            byte[] logo = dataSourceEntity.getLogoIcon();
//            //处理logoicon字段,删除和上传logo时候进入  xin 2019-11-9 16:45:38
//            if(logodel!=null && logodel.equals("1") || logo!=null){
//                //给false值是为了在sql组装的时候处理logoicon字段  xin 2019-11-9 16:45:38
//                dataSourceEntity.setHasLogoIcon(false);
//            }else{
//                dataSourceEntity.setHasLogoIcon(true);
//            }
            if(logoFile!=null && !logoFile.isEmpty()) {//上传文件不为空
                dataSourceEntity.setLogoIcon(logoFile.getBytes());
                dataSourceEntity.setHasLogoIcon(false);
            }
            Integer ret = dIfc.saveDemo(dataSourceEntity);
            if (ret != null && ret.equals(1)) {
                json.addProperty("success", "更新成功!");
            }else {
                json.addProperty("success", "更新失败!");
            }
            //AsynchronousExecution.doRefreshUri(hostUrl,"/SyncDataSource.do?"+SessionKey.DATA_BASE_ID + "=" + dataSourceEntity.getDbId(), "");  //doRefreshDataSource();
 
            refreshDataSource(dataSourceEntity.getDbId()+"",DataSourceActionEntity.ActionEnum.REFRESH);  //直接刷新本机
 
            this.printJson(response, json.toString());
            return;
        }catch (DataAccessException e) {
            e.printStackTrace();
            errJson.addProperty("warning", e.getCause().getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        } catch (Exception e) {
            e.printStackTrace();
            errJson.addProperty("warning", e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        }finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    @RequestMapping("/setXml.do")//(旧方法,下面的/newsetXml.do为最新调用方法) xin 2020-12-28 16:12:39
    public void setXml(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String testConn = request.getParameter("testConn");
        String chqi = request.getParameter("chqi");
        String logodel = request.getParameter("logodel");//logo删除 ,1表示删除 0不处理  xin 2019-11-9 16:45:38
        if (chqi != null) {
            reStartTomcat(request, response);
            return;
        }
        DataSourceEntity dataSourceEntity = null;
        try {
            SpObserver.setDBtoDemo();
            dataSourceEntity = getConnMap(request,response, "");
            String pwd = dataSourceEntity.getPassword();
            if (pwd == null || pwd.equals("")) {
                List<DataSourceEntity> dataSourceMap = demoIfc.getDataSource(
                        DemoConstant.getInstance().setActived(null).setDbId(dataSourceEntity.getDbId() + ""));
                if (dataSourceMap != null && dataSourceMap.size() > 0) {
                        pwd = dataSourceMap.get(0).getPassword();
                        dataSourceEntity.setPassword(pwd);                                    
                }
            }
            byte[] logo = dataSourceEntity.getLogoIcon();
            //处理logoicon字段,删除和上传logo时候进入  xin 2019-11-9 16:45:38
            if(logodel!=null && logodel.equals("1") || logo!=null){
                //给false值是为了在sql组装的时候处理logoicon字段  xin 2019-11-9 16:45:38
                dataSourceEntity.setHasLogoIcon(false);
            }else{
                dataSourceEntity.setHasLogoIcon(true);
            }
            if (dataSourceEntity.getActived()) {
                String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
                String driverUrl = "jdbc:sqlserver://" + dataSourceEntity.getHost() + ":" + dataSourceEntity.getPort()
                        + ";encrypt=true;trustServerCertificate=true;databaseName=" + dataSourceEntity.getDb();
                try {
                    boolean isTestSuccess = DBHelper.getConnTest(driver, driverUrl, dataSourceEntity.getUserid(), pwd);
                    if (!isTestSuccess) {
                        this.print(response,"{\"state\":2,\"info\":\"数据库连接失败!\"}");
                        return;
                    }
                    if (testConn != null && testConn.equals("1")) {
                        this.print(response,"{\"state\":1,\"info\":\"连接成功\"}");
                        return;
                    }
                }catch (Exception e) {
                    this.print(response,"{\"state\":2,\"info\":\""+ (e.getCause() != null?e.getCause().getMessage():e.getMessage()) + "\"}");
                    return;
                }
            }
        } catch (DataAccessException e) {
            this.print(response,"{\"state\":0,\"info\":\"修改出错!错误原因:"+ (e.getCause()!=null?e.getCause().getMessage():e.getMessage())+"\"}");
            return;
        } catch (Exception e) {
            this.print(response,"{\"state\":0,\"info\":\"修改出错!错误原因:"+ (e.getCause()!=null?e.getCause().getMessage():e.getMessage())+"\"}");
            return;
        } finally {
            SpObserver.setDBtoInstance();
        }
 
        try {
            if (dataSourceEntity.getDemoDataSource() != null
                    && (dataSourceEntity.getDemoDataSource()).equals(SpObserver.DEMOXML)) {// demo
                xmlDoWrite(request, dataSourceEntity); // 写入 _demo.xml 文件
                MultiDataSource multiDataSource = (MultiDataSource) FactoryBean.getBean("multiDataSource");
                DemoConstant demoConstant=new DemoConstant();
                demoConstant.setDbId(dataSourceEntity.getDbId()+"");
                multiDataSource.setDataSourceByMap(dataSourceEntity,demoConstant);
                this.print(response,"{\"state\":1,\"info\":\"操作已经处理,请手动重启服务器才能生效!\"}");
            } else {
                // 配置不保存
                String result=null;
                try {
                    SpObserver.setDBtoDemo();
                    String invitationCode = (dataSourceEntity.getInvitationCode() == null ? null
                            : dataSourceEntity.getInvitationCode());
                    if (invitationCode == null || invitationCode.equals("")) {
                        invitationCode = dIfc.getInvitationCode();
                        dataSourceEntity.setInvitationCode(invitationCode);
                    }
                     result = dIfc.updateDemo(dataSourceEntity);
                } finally {
                    SpObserver.setDBtoInstance();
                }
                if(StringUtils.isNotBlank(result)) {
                    refreshDataSource(result.split(",")[0] , DataSourceActionEntity.ActionEnum.REFRESH); // 直接刷新本机
                    if (dataSourceEntity.getActived()) {
                        this.print(response, "{\"state\":1,\"info\":\"修改成功,可立即使用该数据源登录系统!\"}");
                    } else {
                        this.print(response, "{\"state\":1,\"info\":\"修改成功,由于该数据源未【启用】,因此不可立即使用该数据源登录系统!\"}");
                    }
                }
            }
            return;
        } catch (DataAccessException e) {
            this.print(response,"{\"state\":0,\"info\":\"修改出错!错误原因:" + (e.getCause()!=null?e.getCause().getMessage():e.getMessage())+"\"}");
            return;
        } catch (Exception e) {
            this.print(response,"{\"state\":0,\"info\":\"修改出错!错误原因:" + (e.getCause()!=null?e.getCause().getMessage():e.getMessage())+"\"}");
            return;
        }
    }
 
    /**
     * 解析数据源定义的所有域名对应的IP
     * @param dataSourceEntity
     * @return
     */
    private  void processDomainToIP(DataSourceEntity dataSourceEntity){
        StringBuilder sb=new StringBuilder();
        if(StringUtils.isNotBlank(dataSourceEntity.getDomain())) {
             Object[] domainList=  Arrays.stream(dataSourceEntity.getDomain().replaceAll(":.*?\\d+", "").split(";")).distinct().toArray();
            for(Object domain:domainList){
                try {
                    InetAddress addresses = InetAddress.getByName(String.valueOf(domain));
                    //本机IP跳过
                    if("127.0.0.1".equals(addresses.getHostAddress())) continue;
                    sb.append(addresses.getHostAddress());
                        sb.append(";");
                }catch (Exception ex){
                    ex.printStackTrace();
                    continue;
                }
            }
        }
        if(sb.length()>0) {
            String str=sb.toString();
            int index=str.lastIndexOf(";");
            dataSourceEntity.setDomainIpList(str.substring(0,index));
        }
    }
    @RequestMapping("/demo/refreshIp.do")
    public  void freshDomainTOIP(HttpServletRequest request,HttpServletResponse response){
        //通过域名查出ip
        try {
            StringBuilder sql=new StringBuilder();
            final Map<String, DataSourceEntity> dataSourceMaps = MultiDataSource.getDataSourceMaps();
            Map<String, DataSourceEntity> concurrentHashMap =new ConcurrentHashMap<>();
            concurrentHashMap.putAll(dataSourceMaps);
            for (Map.Entry<String, DataSourceEntity> entry : concurrentHashMap.entrySet()) {
                DataSourceEntity dataSourceEntity = entry.getValue();
                    processDomainToIP(dataSourceEntity);
                    sql.append(String.format(" update a set a.domainIpList='%s' from gsystem a where a.id=%d \n ", dataSourceEntity.getDomainIpList(), dataSourceEntity.getDbId()));
            }
                //更新到数据库
                SpObserver.setDBtoDemo();
            if(StringUtils.isNotBlank(sql)) {
                BaseService baseService = (BaseService) FactoryBean.getBean("BaseService");
                baseService.getSimpleJdbcTemplate().execute(sql.toString());
                //刷新数据源
                refreshDataSource("", ActionEnum.REFRESH);
                this.print(response, "所有数据源域名重新绑定IP成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.print(response, new CallBackMessage().sendErrorMessage(e.getMessage()));
        }finally {
            SpObserver.setDBtoInstance();
        }
    }
    //新的保存,修改,测试 xin 2020-12-28 10:25:12
    @RequestMapping("/newsetXml.do")
    public void newsetXml(MultipartFile logoFile, DataSourceEntity datasoure, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try {
            int restart = (request.getParameter("restart")!=null?Integer.parseInt(request.getParameter("restart")):-1);//是否重启
            if (restart!=-1) {
                //重启
                reStartTomcat(request, response);
                return;
            }                
            int saveSystemConfig=(request.getParameter("saveSystemConfig")!=null?Integer.parseInt(request.getParameter("saveSystemConfig")):-1);//
            if(saveSystemConfig!=-1) {
                //维护系统配置界面调用
                saveSystemConfig(logoFile,datasoure,request,response);
                return;
            }
            SpObserver.setDBtoDemo();
            String pwd = datasoure.getPassword();
            if (pwd == null || pwd.equals("")) {// 密码为空时,查询数据库获取密码
                List<DataSourceEntity> dataSourceMap = demoIfc
                        .getDataSource(DemoConstant.getInstance().setActived(null).setDbId(datasoure.getDbId() + ""));
                if (dataSourceMap != null && dataSourceMap.size() > 0) {
                    pwd = dataSourceMap.get(0).getPassword();
                    datasoure.setPassword(pwd);
                }
            }else {
                datasoure.setPassword(ChangePassword.getEncryptPassword(pwd));//密码加密
            }
            if (datasoure.getActived()) {
                String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
                String driverUrl = "jdbc:sqlserver://" + datasoure.getHost() + ":" + datasoure.getPort()
                        + ";encrypt=true;trustServerCertificate=true;databaseName=" + datasoure.getDb();
                try {
                    boolean isTestSuccess = DBHelper.getConnTest(driver, driverUrl, datasoure.getUserid(), datasoure.getPassword());
                    if (!isTestSuccess) {
                        super.print(response, new CallBackMessage().sendErrorMessage("数据库连接失败!"));
                        return;
                    }
                    String testConn = request.getParameter("testConn");//测试连接
                    if (testConn != null && testConn.equals("1")) {
                        super.print(response, new CallBackMessage().sendSuccessMessage("连接成功"));
                        return;
                    }
                } catch (Exception e) {
                    super.print(response, new CallBackMessage()
                            .sendErrorMessage((e.getCause() != null ? e.getCause().getMessage() : e.getMessage())));
                    return;
                }
            }
            if(logoFile!=null && !logoFile.isEmpty()) {//上传文件不为空
                datasoure.setLogoIcon(logoFile.getBytes());
                datasoure.setHasLogoIcon(false);
            }
 
            if (datasoure.getDemoDataSource() != null && (datasoure.getDemoDataSource()).equals(SpObserver.DEMOXML)) {// demo
                xmlDoWrite(request, datasoure); // 写入 _demo.xml 文件
                MultiDataSource multiDataSource = (MultiDataSource) FactoryBean.getBean("multiDataSource");
                DemoConstant demoConstant=new DemoConstant();
                demoConstant.setDbId(datasoure.getDbId()+"");
                multiDataSource.setDataSourceByMap(datasoure,demoConstant);
                this.print(response, new CallBackMessage().sendSuccessMessage("操作已经处理,请手动重启服务器才能生效!"));
                return;
            } else {
                // 配置不保存
                String invitationCode = (datasoure.getInvitationCode() == null ? null : datasoure.getInvitationCode());
                if (invitationCode == null || invitationCode.equals("")) {
                    invitationCode = dIfc.getInvitationCode();
                    datasoure.setInvitationCode(invitationCode);
                }
                //解析域名对应的IP
                processDomainToIP(datasoure);
                String result = dIfc.updateDemo(datasoure);
                if(StringUtils.isNotBlank(result)) {
                    String[] arrayResult=result.split(",");
                    String dbid=arrayResult[0];
                    String expiredMinute=arrayResult[1];
                    refreshDataSource(dbid , DataSourceActionEntity.ActionEnum.REFRESH); // 直接刷新本机
                    if (Integer.parseInt(expiredMinute)>=0) {
                        //过期则发通知退出系统返回登录页面 by danaus 2022/8/2 16:57
                        MessageInfo messageInfo = new MessageInfo();
                        messageInfo.setDbId(datasoure.getDbId());
                        messageInfo.setMsgType(MessageType.NOTICE_SYSTEM_STOP);
                        WebSocketMessageServer.publishMessageToRedis(messageInfo);
                    }
                    String datav = "{\"dbid\":" + dbid + ",\"invitationCode\":\"" + datasoure.getInvitationCode() + "\"}";
                    File file = new File(request.getSession().getServletContext().getRealPath(File.separator + "images" + File.separator + "login" + File.separator + dbid + File.separator + "logo.png"));
                    if (!logoFile.isEmpty()) {//修改成功后,再次把logo图片写入磁盘里 xin 2021-4-14 14:15:11
                        if (!file.getParentFile().exists() || !file.exists()) {//表示文件或目录是否存在
                            file.getParentFile().mkdirs();
                            file.createNewFile();
                        }
                        ImageIO.write(ImageIO.read(logoFile.getInputStream()), "png", file);
                    } else {
                        if (!datasoure.isHasLogoIcon() && file.exists()) {//默认图片情况下把上传过的图片删除
                            file.delete();//删除
                        }
                    }
                    if (datasoure.getActived()) {
                        this.print(response, new CallBackMessage().setData(datav).sendSuccessMessage("修改成功,可立即使用该数据源登录系统!"));
                    } else {
                        this.print(response,
                                new CallBackMessage().setData(datav).sendSuccessMessage("修改成功,由于该数据源未【启用】,因此不可立即使用该数据源登录系统!"));
                    }
                    return;
                }
            }
        } catch (Exception e) {
            super.print(response, new CallBackMessage()
                    .sendErrorMessage((e.getCause() != null ? e.getCause().getMessage() : e.getMessage())));
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
    
    //Logo图片加载--- xin 2019-10-31 17:59:44    
    @RequestMapping("/getLogoIcon.do")
    @SuppressWarnings("all")
    private void getLogoIcon(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int dbid = Integer.parseInt(request.getParameter("dbid"));
        BufferedImage bufImg = null;
        File file = new File(request.getSession().getServletContext().getRealPath(File.separator + "images" + File.separator + "login" + File.separator + dbid + File.separator + "logo.png"));
//        if (!file.getParentFile().exists() || !file.exists()) {//表示文件或目录是否存在
            file.getParentFile().mkdirs();
            file.createNewFile();
            String mrPath = request.getSession().getServletContext().getRealPath(File.separator + "images" + File.separator + "login" + File.separator + "logo.png");
            try {
                SpObserver.setDBtoDemo();
                String sql = " set nocount on \n" + " declare @dbid int = ? \n";
                sql += "select LogoIcon from gsystem where id = @dbid ";
                BaseService baseServer = (BaseService) FactoryBean.getBean("BaseService");
                Map<String, Object> logo = baseServer.getJdbcTemplate().queryForMap(sql, new Object[]{dbid});
                if (logo != null && logo.get("LogoIcon") != null && !"".equals(logo.get("LogoIcon"))) {
                    ByteArrayInputStream input=new ByteArrayInputStream((byte[]) logo.get("LogoIcon"));
                    try {
                        bufImg = ImageIO.read(input);
                    } catch (IIOException iioException) {
                        bufImg = makeGrey(input, mrPath);
                    }
                } else {
                    bufImg = ImageIO.read(new File(mrPath));
                }
                ImageIO.write(bufImg, "png", response.getOutputStream());
            } catch (Exception e) {
                bufImg = ImageIO.read(new File(mrPath));
                ImageIO.write(bufImg, "png", response.getOutputStream());
            } finally {
                SpObserver.setDBtoInstance();
                ImageIO.write(bufImg, "png", file);
            }
//        } else {
//            ImageIO.write(ImageIO.read(file), "png", response.getOutputStream());
//        }
    }
 
    //对图片做灰化处理
    public static BufferedImage makeGrey(ByteArrayInputStream in,String mrPath) throws IOException {
        ImageInputStream input = ImageIO.createImageInputStream(in);
        Iterator<?> readers = ImageIO.getImageReaders(input);
        if (readers == null || !readers.hasNext()) {
            return ImageIO.read(new File(mrPath));
        }
        ImageReader reader = (ImageReader) readers.next();
        reader.setInput(input);
        // 读取Raster (没有颜色的转换).
        Raster raster = reader.readRaster(0, null);
        BufferedImage img = new BufferedImage(raster.getWidth(), raster.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
        img.getRaster().setRect(raster);
        BufferedImage bufferedImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
        bufferedImage.getGraphics().drawImage(img, 0, 0, img.getWidth(), img.getHeight(), null);
        bufferedImage = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB), null).filter(img, bufferedImage);
        return bufferedImage;
    }
 
    /**
     * 重启服务器
     *
     * @param request
     * @param out
     * @throws LifecycleException
     */
    private void reStartTomcat(HttpServletRequest request, HttpServletResponse response) throws LifecycleException {
        EMBEDDED.stop();
        try {
            EMBEDDED.start();
        } catch (Exception e) {
            // e.printStackTrace();
            DBHelper.log.debug("脚本启动服务时");
        } finally {
            // out.print("已经生成配置文件!必须重启服务,否则还是用原配置!");
            request.getSession().setAttribute(SessionKey.DEMO_REF, null);// 处理之后无权限控制配置文件
            this.print(response,"可以再操作了!");
        }
    }
 
    public static boolean isNumberic(String str) {
        if (str == null || "".equals(str)) return false ;
        //检查字符串是否数字
        for (int k = str.length();--k>=0;){
            if (!Character.isDigit(str.charAt(k))){
                return false ;
            }
        }
        return true ;
    }
 
    /**
     * 获得连接设置参数
     *
     * @param request
     * @return Map<String, Object>
     * @throws Exception
     */
    private DataSourceEntity getConnMap(HttpServletRequest request1, HttpServletResponse response, String i)
            throws Exception {
        DataSourceEntity dataSourceEntity = new DataSourceEntity();
        // 创建SmartUpload对象
        SmartUpload Upload = new SmartUpload();
        try {
            // ------------获取logo图片值            
            // 初始化SmartUpload对象
            Upload.initialize(request1.getServletContext(), request1, response);
            // 设置允许上传文件类型
            Upload.setAllowedFilesList("jpg,gif,jpeg,png");
            //设置上传文件的最大值
            Upload.setMaxFileSize(1024*1024);
              //设置上传文件的总最大值
            Upload.setTotalMaxFileSize(1024*1024);
            // 上传
            Upload.upload();
            Files files = Upload.getFiles();
            com.jspsmart.upload.File file = null;
            for (int f = 0; f < files.getCount(); f++) { // 遍历上传的所有文件
                file = files.getFile(f);
            }
            if (file!=null && !file.getFileName().equals("")) {
                String path = EnvHelper.getPath() + EnvHelper.getJrxml();
                Upload.save(path);
                File file2 = new File(path + file.getFileName());
                dataSourceEntity.setLogoIcon(input2byte(new FileInputStream(file2)));
                if(file2!=null&&file2.exists()&& file2.isFile()) {
                    log.info("del>>userCode:"+request1.getSession().getAttribute(SessionKey.USERCODE)+"|dbid:"+request1.getSession().getAttribute(SessionKey.DATA_BASE_ID)+"|"+file2.getAbsolutePath());
                    file2.delete();
                }
            }
            Request request = Upload.getRequest();
            // -----end
 
            String password = request.getParameter(DemoKey._PASSWORD + i);
            if (password != null && !"".equals(password)) {
                password = ChangePassword.getEncryptPassword(password);
            } else {
                password = "";
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String expiredDateStr = request.getParameter("expiredDate");
            Date expiredDate = null;
            try {
                if (expiredDateStr != null && !"".equals(expiredDateStr)) {
                    expiredDate = sdf.parse(expiredDateStr);
                }
            } catch (ParseException px) {
                throw px;
            }
            String dbId = request.getParameter(DemoKey._ID + i);
 
            if (isNumberic(dbId)) {
                dataSourceEntity.setDbId(Integer.parseInt(dbId));
            } else {
                dataSourceEntity.setDemoDataSource(SpObserver.DEMOXML);
            }
 
            dataSourceEntity.setDb(request.getParameter(DemoKey._DB + i))
                    .setHost(request.getParameter(DemoKey._HOST + i)).setPassword(password)
                    .setPort(request.getParameter(DemoKey._PORT + i))
                    .setUserid(request.getParameter(DemoKey._USER_ID + i))
                    .setActived(request.getParameter(DemoKey._ACTIVED + i) != null
                            && "1".equals(request.getParameter(DemoKey._ACTIVED + i)) ? true : false)
                    .setSystemID(request.getParameter(DemoKey._SYSTEM_ID + i))
                    .setSystemDescribe(request.getParameter(DemoKey._SYSTEM_DESCRIBE + i))
                    .setDomain(request.getParameter(DemoKey._DOMAIN)).setSmsUid(request.getParameter("smsUid"))
                    .setSmsKey(request.getParameter("smsKey"))
                    .setLimitUserNumber(request.getParameter("LimitUserNumber") != null
                            && !request.getParameter("LimitUserNumber").equals("")
                                    ? Integer.parseInt(request.getParameter("LimitUserNumber")) : 0)
                    .setLimitDepartmentNumber(request.getParameter("LimitDepartmentNumber") != null
                            && !request.getParameter("LimitDepartmentNumber").equals("")
                                    ? Integer.parseInt(request.getParameter("LimitDepartmentNumber")) : 0)
                    .setSystemType(request.getParameter("systemtype")).setExpiredDate(expiredDate)
                    .setShowAttendanceButton(request.getParameter("isShowAttendanceButton") != null
                            && "1".equals(request.getParameter("isShowAttendanceButton")) ? true : false)
                    .setRemarks(request.getParameter("Remarks"))
                    .setDataCheckPageNum(request.getParameter("DataCheckPageNum") != null
                            && !"".equals(request.getParameter("DataCheckPageNum"))
                                    ? Integer.parseInt(request.getParameter("DataCheckPageNum")) : 0)
                    .setCorpURL(request.getParameter("CorpURL")).setCorpId(request.getParameter("CorpId"))
                    .setMpAppId(request.getParameter("MpAppId")).setMpSecret(request.getParameter("MpSecret"))
                    .setMpToken(request.getParameter("MpToken")).setMpAesKey(request.getParameter("MpAesKey"))
                    .setMpOrgId(request.getParameter("MpOrgId")).setMiniAppId(request.getParameter("MiniAppId"))
                    .setMiniAppSecret(request.getParameter("MiniAppSecret"))
                    .setMiniAppToken(request.getParameter("MiniAppToken"))
                    .setMiniAppAesKey(request.getParameter("MiniAppAesKey"))
                    .setMiniAppOrgId(request.getParameter("MiniAppOrgId")).setMpMchId(request.getParameter("MpMchId"))
                    .setMpMchName(request.getParameter("MpMchName")).setMpMchKey(request.getParameter("MpMchKey"))
                    .setGeoWebApiKey(request.getParameter("GeoWebApiKey"))
                    .setInvitationCode(request.getParameter("InvitationCode"))                    
                    .setDisabledOpenNextPeriodId(request.getParameter("isDisabledOpenNextPeriodId") != null
                            && "1".equals(request.getParameter("isDisabledOpenNextPeriodId")) ? true : false)
                    .setSystemSecretKey(request.getParameter("SystemSecretKey"))
                    .setSystemAccessKey(request.getParameter("SystemAccessKey"))
                    .setDockingSystem(request.getParameter("DockingSystem"))
                    .setUseAPP(request.getParameter("isUseAPP") != null && "1".equals(request.getParameter("isUseAPP"))
                            ? true : false)
                    .setShowInLoginPage(request.getParameter("isShowInLoginPage") != null
                            && "1".equals(request.getParameter("isShowInLoginPage")) ? true : false)
                    .setProtocol(request.getParameter("Protocol")) 
                    .setAutoGenerateFormId(request.getParameter("isAutoGenerateFormId")!=null && "1".equals(request.getParameter("isAutoGenerateFormId"))?true:false)
                    .setTengXunMapLocationServiceKey(request.getParameter("TengXunMapLocationServiceKey"));
 
            return dataSourceEntity;
        } catch (Exception e) {
            String error=(e.getCause()!=null?e.getCause().getMessage():e.getMessage());
            if(error!=null && error.indexOf("1010")!=-1){
                error="只能上传JPG,GIF,JPEG,PNG格式,并且图片大小在1M以内。";
            }
            throw new Exception(error);
        } finally {
        }
    }
 
 
    /**
     * 生成一个连接文件
     *
     * @param map 所需集合信息
     */
    private void xmlDoWrite(HttpServletRequest request,DataSourceEntity dataSourceEntity)  throws Exception{
 
 
        //String jdbcUrl = DBHelper.encryptHelper.encrypt("jdbc:jtds:sqlserver://" + DBHelper.getValue(map, DemoKey._HOST) + ":" + DBHelper.getValue(map, DemoKey._PORT) + ";DatabaseName=" + DBHelper.getValue(map, DemoKey._DB)) ;
        String user = DBHelper.encryptHelper.encrypt(dataSourceEntity.getUserid()) ;
        String password = dataSourceEntity.getPassword();  // DBHelper.encryptHelper.encrypt(DBHelper.encryptHelper.encrypt(DBHelper.getValue(map, DemoKey._PASSWORD))) ;
 
        StringBuffer sBuffer = new StringBuffer();
        sBuffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sBuffer.append("\n<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\" \"http://www.springframework.org/dtd/spring-beans.dtd\">");
        sBuffer.append("\n<beans>");
        sBuffer.append("\n   <bean id=\"" + dataSourceEntity.getDemoDataSource()  + "\" class=\"com.yc.dataAccess.ComboPooledDataSource\" destroy-method=\"close\">  ");
 
        //sBuffer.append("\n        <property name=\"driverClass\" value=\"" + DBHelper.encryptHelper.encrypt("net.sourceforge.jtds.jdbc.Driver") + "\"/>");
        //sBuffer.append("\n            <property name=\"jdbcUrl\" value=\"" + jdbcUrl + "\"/>");
        sBuffer.append("\n        <property name=\"driverClass\" value=\"" + DBHelper.encryptHelper.encrypt(driverClass) + "\"/>");
        sBuffer.append("\n            <property name=\"jdbcUrl\" value=\"" + DBHelper.encryptHelper.encrypt("jdbc:sqlserver://" +dataSourceEntity.getHost() + ":" +dataSourceEntity.getPort() + ";encrypt=true;trustServerCertificate=true;databaseName=" +dataSourceEntity.getDb()) + "\"/>");
 
 
        sBuffer.append("\n             <property name=\"user\" value=\"" + user + "\"/>");
        sBuffer.append("\n            <property name=\"password\" value=\"" + password + "\"/>");
        sBuffer.append("\n            <property name=\"initialPoolSize\" value=\""+ initialPoolSize +"\"/>");
        sBuffer.append("\n            <property name=\"minPoolSize\" value=\""+ minPoolSize +"\"/>");
        sBuffer.append("\n            <property name=\"maxPoolSize\" value=\"" + maxPoolSize+"\"/>");
        sBuffer.append("\n            <property name=\"acquireIncrement\" value=\"" + acquireIncrement+ "\"/>");
        sBuffer.append("\n            <property name=\"maxIdleTime\" value=\"" + maxIdleTime + "\"/>");
        sBuffer.append("\n            <property name=\"idleConnectionTestPeriod\" value=\"" + idleConnectionTestPeriod + "\"/>");
        sBuffer.append("\n            <property name=\"maxStatements\" value=\"" + maxStatements + "\"/>");
        sBuffer.append("\n   </bean>");
        sBuffer.append("\n</beans>");
        try {
            FAFO.writeFile(EnvHelper.getPath() + File.separator+"WEB-INF"+File.separator+"classes"+File.separator+"dataSource"+File.separator+ dataSourceEntity.getDemoDataSource()  + ".xml", sBuffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @RequestMapping("/doDelDemo.do")
    public void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int dbid = Integer.parseInt(request.getParameter("op").toString());
        //String hostUrl = SettingKey.getHostUrl(request) ;
        JsonObject json = new JsonObject();
        try {
            SpObserver.setDBtoDemo();
            dIfc.deleteDemo(dbid);
            DBHelper.cDao.delete(EnvHelper.getPath() + File.separator+"WEB-INF"+File.separator+"classes"+File.separator+"dataSource"+File.separator+"_" + dbid + ".xml");
            //AsynchronousExecution.doRefreshUri(hostUrl,"/SyncDataSource.do?"+SessionKey.DATA_BASE_ID + "=" + dbid , "");
 
            refreshDataSource(dbid+"",DataSourceActionEntity.ActionEnum.DELETE);  //直接刷新本机
            json.addProperty("hint", "删除成功!");
            this.printJson(response, json.toString());
        } catch (Exception e) {
            e.printStackTrace();
            json.addProperty("error", e.getCause()!= null?e.getCause().getMessage(): e.getMessage());
            this.printJson(response, json.toString());
            return ;
        } finally {
            SpObserver.setDBtoInstance();
        }
        
    }
 
    @RequestMapping("/getDyfied.do")
    public void getDyfield(String headflag, String funcname, String fs, HttpServletRequest request, HttpServletResponse response) throws IOException, Exception {
 
        String string = "select *,controltype=3 from " + funcname + fs + " where headflag=" + headflag;
        try {
            SpObserver.setDBtoInstance("_"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID));
        List<Map<String, Object>> list = sqlDBHelperIfc.getHashMapObj(string);
        String listmax = gridServiceIfc.getTypeLengthInfo(funcname + fs);
        Map<String, Integer> maxMap = new HashMap<String, Integer>();
        // 返回char nchar,varchar nvarchar类型的字段和长度。操作时间:2014-7-2 16:39:42
        if (listmax != null) {
            String[] max = listmax.split(",");
            for (int m = 0; m < max.length; m++) {
                String[] maindex = max[m].split("-");
                maxMap.put(maindex[0], Integer.parseInt(maindex[1]));// 组装字段和长度 操作时间:2014-7-2 16:39:29
            }
        }
        String writeHtml = "";
        PanelParmHelper parmHelper = null;
        PanelBean panelBean=null;
        for (Map<String, Object> map : list) {
            if (DBHelper.getValueInt(map, "visible") == 1) {
                String yeId = DBHelper.getValue(map, "fieldid");
                //----start by danaus 2020/2/20 12:12
                parmHelper = new PanelParmHelper();
                parmHelper.id = yeId;
                panelBean=new PanelBean();
                panelBean.setPHelper(parmHelper);
                map.put(TypeControl.PANEL_INFO,panelBean);//把panelBean加到map,进行下一步处理
                //----end
                writeHtml = yeId + ";pb#1;pb#" + tControlDao.getComponentForPanel(map, false, maxMap) + ";fen#";// 创建控件
            } else {
                writeHtml = DBHelper.getValue(map, "fieldid") + ";pb#0;fen#";
            }
            this.print(response,writeHtml);
        }
        
    }catch (Exception e) {
        this.print(response, e.getCause()!=null?e.getCause().getMessage():e.getMessage());
    }finally {
        SpObserver.setDBtoInstance();
    }
    }
 
    @RequestMapping("/doCompany.do")
    public void doCompany(HttpServletRequest request, HttpServletResponse response) throws IOException, Exception {
        try {
            int cltId = Integer.parseInt(request.getParameter("cltId"));
            int statuid = Integer.parseInt(request.getParameter("statuid"));
            HttpSession session = request.getSession();
            String hostUrl = SettingKey.getHostUrl(request) ;
            Integer dbid = null;
            //FileDo fDo = new FileDo();
 
            DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMapByCltId( cltId) ;
 
            if (statuid == 0) {// 未开通时执行的步骤
                String exeSql = "exec pCreateDB " + cltId + ",'" + session.getAttribute(SessionKey.USERCODE) + "','" + session.getAttribute(SessionKey.USERNAME) + "'";
 
                try {
                    SpObserver.setDBtoDemo();// 更改到demo数据库
                    sqlDBHelperIfc.dataSql(exeSql);// 第一部 还原数据库
                    //map = dIfc.getOneByCltId(cltId);
                } catch (Exception e) {
                    throw new ApplicationException(e.getMessage());
                } finally {
                    SpObserver.setDBtoInstance();
                }
                if (dataSourceEntity != null) {
 
                    dataSourceEntity.setActived(true);
 
                    try {
                        SpObserver.setDBtoDemo();// 更改到demo数据库
                        dbid = dIfc.updateDemoSaaS(dataSourceEntity);// 第二步 重新更改
                    } catch (Exception e) {
                        throw new ApplicationException(e.getMessage());
                    } finally {
                        SpObserver.setDBtoInstance();
                    }
 
                    // AsynchronousExecution.doRefreshUri(hostUrl,"/SyncDataSource.do?"+SessionKey.DATA_BASE_ID + "=" + dbid , "");
 
                    refreshDataSource(dbid+"",DataSourceActionEntity.ActionEnum.REFRESH);  //直接刷新本机
 
 
                    //fDo.copy(EnvHelper.getPath() + "app"+File.separator + map.get(DemoKey._TEMP_CONNID), EnvHelper.getPath() + "app"+File.separator + map.get(DemoKey._ID));// 第三步 生成开通的源文件
 
                    //MultiDataSource multiDataSource = (MultiDataSource) FactoryBean.getBean("multiDataSource");
                    //multiDataSource.refreshDataSource(dbid+"");
                }
            } else if (statuid == 5) {// 删除时执行
                try {
                    SpObserver.setDBtoDemo();
                    //map = dIfc.getOneByCltId(cltId);
                } finally {
                    SpObserver.setDBtoInstance();
                }
                if (dataSourceEntity != null) {
 
                    dataSourceEntity.setActived(false);
 
 
                    String exeSql = "exec pDropDB " + cltId + ",'" + session.getAttribute(SessionKey.USERCODE) + "','" + session.getAttribute(SessionKey.USERNAME) + "'";
                    try {
                        SpObserver.setDBtoDemo();// 更改到demo数据库
                        dbid = dIfc.updateDemoSaaS(dataSourceEntity);// 第一步 重新更改
                        sqlDBHelperIfc.dataSql(exeSql);// 第二步 删除数据库
                    } catch (Exception e) {
                        throw new ApplicationException(e.getMessage());
                    } finally {
                        SpObserver.setDBtoInstance();
                    }
 
                    AsynchronousExecution.doRefreshUri(hostUrl,"/SyncDataSource.do?"+SessionKey.DATA_BASE_ID + "=" + dbid , "");
 
                    refreshDataSource(dbid+"",DataSourceActionEntity.ActionEnum.REFRESH);  //直接刷新本机
 
                    //fDo.delete(EnvHelper.getPath() + "app" +File.separator + map.get(DemoKey._ID));// 第三步删除原文件
                    //multiDataSource.reflshDB(dbid+"", "0");
                }
            } else {// 2,3,4
 
                if (dataSourceEntity != null) {
 
                    try {
                        SpObserver.setDBtoDemo();// 更改到demo数据库
                        sqlDBHelperIfc.doSql("update  a  set a.actived=0 from gsystem a where a.CltID =" + dataSourceEntity.getCltId());
                    } catch (Exception e) {
                        throw new ApplicationException(e.getMessage());
                    } finally {
                        SpObserver.setDBtoInstance();
                    }
                    AsynchronousExecution.doRefreshUri(hostUrl,"/SyncDataSource.do?"+SessionKey.DATA_BASE_ID + "=" + dbid , "");
 
                    refreshDataSource(dbid+"",DataSourceActionEntity.ActionEnum.REFRESH);  //直接刷新本机
 
                    //multiDataSource.reflshDB(dataSourceEntity.getId()+"", "0");
                }
            }
 
            statuid = (statuid == 0 ? 1 : statuid);
            try {
                SpObserver.setDBtoDemo();// 更改到demo数据库
                sqlDBHelperIfc.doSql("update a set status =" + statuid + " from _sysCustomer a where CltID =" + cltId);
                this.print(response,"1");
            } catch (Exception e) {
                throw new ApplicationException(e.getMessage());
            } finally {
                SpObserver.setDBtoInstance();
            }
 
        } catch (Exception e) {
            String mesString = (e.getCause() != null) ? e.getCause().getMessage() : e.getMessage();
            this.print(response,mesString);
        } 
 
    }
}