johnswang
2022-01-15 22907b8763fc073011872b637dc23023ef7fb4f4
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
package com.yc.sdk.weixincp.action;
 
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.Map.Entry;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.http.HttpSession;
 
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.Gender;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpUser;
 
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 com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.yc.action.BaseAction;
import com.yc.entity.DataSourceEntity;
import com.yc.entity.attachment.AttachmentWhereEntity;
import com.yc.multiData.MultiDataSource;
import com.yc.multiData.SpObserver;
import com.yc.sdk.miniapp.action.MaServiceInit;
import com.yc.sdk.miniapp.entity.MaSettingEntity;
import com.yc.sdk.miniapp.service.MaSettingIfc;
import com.yc.sdk.shopping.entity.SettingEntity;
import com.yc.sdk.shopping.service.SettingIfc;
import com.yc.sdk.shopping.service.imagedata.ShoppingImageDataIfc;
import com.yc.sdk.shopping.util.SettingKey;
import com.yc.sdk.weixincp.entity.MyWxCpDepart;
import com.yc.sdk.weixincp.entity.MyWxCpUser;
import com.yc.sdk.weixincp.entity.OtherMatEntity;
import com.yc.sdk.weixincp.entity.SaveUserInfoResultEntity;
import com.yc.sdk.weixincp.service.AppIfc;
import com.yc.sdk.weixincp.service.DeptIfc;
import com.yc.sdk.weixincp.service.ERPUserIfc;
import com.yc.sdk.weixincp.service.MaterialIfc;
import com.yc.sdk.weixincp.service.MessagesIfc;
import com.yc.sdk.weixincp.util.AvatarFile;
import com.yc.sdk.weixincp.util.PinyinRec;
import com.yc.sdk.weixincp.util.RandomString;
import com.yc.sdk.weixincp.util.WeiXinMediaType;
import com.yc.sdk.weixincp3rd.entity.SuiteComponentAppEntity;
import com.yc.service.upload.AttachmentIfc;
import com.yc.utils.SessionKey;
 
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
 
 
/**
 * 微信用户管理,与ERP系统同步用户信息
 * 
 * @author JohnsWang
 *
 */
 
@Controller
public class CPUser extends BaseAction {
 
    @Autowired
    ERPUserIfc erpUserIfc;
    @Autowired
    MessagesIfc messagesIfc;
    @Autowired 
    DeptIfc deptIfc ;
    @Autowired 
    MaterialIfc materialIfc ;
    @Autowired
    AppIfc appIfc ;
    @Autowired
    ShoppingImageDataIfc imgData;
    @Autowired
    SettingIfc settingIfc;
    @Autowired
    MaSettingIfc maSettingIfc;
    @Autowired
    private AttachmentIfc attachmentIfc;
 
//    protected WxCpJedisConfigStorage wxCpConfigStorage;
//    protected MyWxCpService wxCpService;
    protected DataSourceEntity corpEntity;
 
    /*
    public void setInit(WxCpJedisConfigStorage wxCpConfigStorage, 
            MyWxCpService wxCpService,DataSourceEntity corpEntity) {
        this.wxCpConfigStorage = wxCpConfigStorage ;
        this.wxCpService = wxCpService ;
        this.corpEntity = corpEntity ;
        
        try {
            SpObserver.setDBtoInstance("_" + corpEntity.getDbId());// 切换数据源
            AppEntity appEntity  = appIfc.getERPAppInfoByCategoryName("通讯录同步助手") ;
            
                if (appEntity == null) {
                    throw new Exception("请在 700101 功能号中维护微信企业应用【通讯录同步助手】,并填写 Secret 字段值\n") ;
                    //response.getWriter().println("请在 700101 功能号中维护微信企业应用【通讯录同步助手】,并填写 Secret 字段值\n");
                    //return ;
                }
            
            
            wxCpConfigStorage.setAgentId(appEntity.getAgentid());
            wxCpConfigStorage.setCorpSecret(appEntity.getCorpAppSecret());
            wxCpConfigStorage.setToken(appEntity.getCorpAppToken()); // 设置微信企业号应用的token
            wxCpConfigStorage.setAesKey(appEntity.getCorpAppAesKey()); // 设置微信企业号应用的EncodingAESKey
        } catch ( Exception e1) {
            e1.printStackTrace();
        }finally {
            SpObserver.setDBtoInstance();
        }
    }*/
    
//    public void setWxCpService(MyWxCpService wxCpService) {
//        this.wxCpService = wxCpService ;
//    }
    
    public void setDataSourceEntity(DataSourceEntity corpEntity) {
        this.corpEntity = corpEntity ;
    }
    
    /**
     * 1.从微信服务器拉取用户信息到ERP系统
     * @param response
     * @param request
     */
    public List<String>  userUpdateByPull(HttpServletRequest request,WxCpService wxCpService) {
        List<String> errList = new ArrayList<String>() ;
        // 将ERP新用户复制微信系统中 ,在复制之前必须先同步部门信息(同步部门要执行 CPDept.java 对象)
        List<MyWxCpDepart> erpDeptInfoList = deptIfc.getDeptInfo() ;
        List<WxCpUser> userListAll = new ArrayList<WxCpUser>() ;
        String userId = "",userName = "";
        try {
            //WxCpService wxCpService = CpServiceInit.getWxCpService(corpEntity.getCorpId(),"addressbook") ;
            for (int i = 0 ;erpDeptInfoList != null && i < erpDeptInfoList.size();i++ ) {
                
                List<WxCpUser> userList = wxCpService.getUserService().listSimpleByDepartment(erpDeptInfoList.get(i).getId(), false, 0) ;
                for (int j = 0 ;userList != null && j < userList.size();j++ ) {
                    WxCpUser wxCpUser = wxCpService.getUserService().getById(userList.get(j).getUserId());
                    if(wxCpUser!=null) {
                        userId = wxCpUser.getUserId();
                        userName = wxCpUser.getName();
                    }
                    SaveUserInfoResultEntity result = null ;
                    try {
                        result = erpUserIfc.saveWorkAppUser(wxCpUser,null);
                    }catch (Exception e) {
                        System.out.println("数据源["+SpObserver.getCurrentInstance()+"]同步用户[" + (wxCpUser!= null? wxCpUser.getUserId():"")+ "]信息时有错误发生(saveWorkAppUser),错误代码:" + (e.getCause()!=null?e.getCause().getMessage(): e.getMessage()));
                        throw e ;
                    }
                    
                    //更新头像
                    if (result != null  && wxCpUser.getAvatar() != null) {  //   && !wxCpUser.getAvatar().equals(result.getAvatar())) {
                        //更新用户头像
                        String avatarMediaIDUri = wxCpUser.getAvatar();  //获取微信图像 uri    
                        if (avatarMediaIDUri != null && !"".equals(avatarMediaIDUri)) {
                            String filePath = request.getServletContext().getRealPath("/") + "uploads"+File.separator+"smallpic"+File.separator ;
                            String fileName = filePath + RandomString.getRandomString(4) +".jpg";
                            File file = AvatarFile.getAvatarFile (avatarMediaIDUri,fileName,filePath) ;  //获取微信图像 File 对象
                            if (file != null) {
                                messagesIfc.saveSubscribeEvent(wxCpUser,corpEntity,file ) ;  //上传图像文件至数据库
                            }
                        }
                    }
                    userListAll.add(wxCpUser) ;
                }
            }
            
            //删除多余的用户
            List<MyWxCpUser> erpUserInfoList = erpUserIfc.getWorkAppUsers();
            for (int i = 0 ;erpUserInfoList != null && i < erpUserInfoList.size();i++) {
                if (!isExistsERPUser(userListAll,erpUserInfoList.get(i).getUserId()) ) {
                    erpUserIfc.deleteWorkAppUser(erpUserInfoList.get(i).getUserId());
                 }
            }
            
        } catch (WxErrorException e) {
            errList.add("同步用户[" + userId+"/" + userName+"]信息时有错误发生,错误代码:" + e.getError().getErrorCode()+",错误信息:" + e.getError().getErrorMsg());
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
            errList.add("同步用户[" + userId+"/" + userName+"]信息时有错误发生,错误代码:" + (e.getCause()!=null?e.getCause().getMessage(): e.getMessage()));
            
        }
        return errList ;
        
    }
    
    /**
     * 2.从ERP系统推送用户信息到微信服务器
     * @param response
     * @param request
     */
    public List<String> userUpdateByPush(HttpServletRequest request,WxCpService wxCpService) {
        List<String> errList = new ArrayList<String>() ;
        // 将ERP新用户复制微信系统中 ,在复制之前必须先同步部门信息(同步部门要执行 CPDept.java 对象)
        List<MyWxCpUser> erpUserInfoList = erpUserIfc.getWorkAppUsers();
        
        
        //1.首先更新存在的用户
        for (int i = 0; erpUserInfoList != null && i < erpUserInfoList.size(); i++) {
            WxCpUser erpUserInfo = erpUserInfoList.get(i);
            
            //如果性别为空 或 mobile/weixinid/email 同时为空,则跳过去
            if (erpUserInfo.getGender() == null || "".equals(erpUserInfo.getGender().getCode()) ||
                    ((erpUserInfo.getEmail() == null || "".equals(erpUserInfo.getEmail())) 
                    && (erpUserInfo.getMobile() == null || "".equals(erpUserInfo.getMobile())) 
                    && (erpUserInfo.getTelephone() == null || "".equals(erpUserInfo.getTelephone()))))
                    continue ;
 
            WxCpUser wxUserInfo = null ; 
            try {
                
                wxUserInfo = wxCpService.getUserService().getById(erpUserInfo.getUserId()) ;
            } catch (WxErrorException e) {
                if (e.getError().getErrorCode() == 60111) continue ;
                String errmsg = "同步用户【"+erpUserInfo.getUserId()+"】【" + erpUserInfo.getName() + "】信息时有错误发生,错误代码:" + e.getError().getErrorCode()+",错误信息:" + e.getError().getErrorMsg();
                errList.add(errmsg);
                e.printStackTrace();
            }
            try {
                if (wxUserInfo != null) {
                    WxCpUser wxCpUser = new WxCpUser() ;
                    wxCpUser.setUserId(erpUserInfo.getUserId());
                    wxCpUser.setName(erpUserInfo.getName()) ;
                    wxCpUser.setDepartIds(erpUserInfo.getDepartIds());
                    wxCpUser.setPosition(erpUserInfo.getPosition());
                    wxCpUser.setMobile(erpUserInfo.getMobile());
                    wxCpUser.setGender(erpUserInfo.getGender());
                    wxCpUser.setEmail(erpUserInfo.getEmail());
                    wxCpUser.setIsLeader(erpUserInfo.getIsLeader());
                    wxCpUser.setEnable(erpUserInfo.getEnable());
                    wxCpUser.setAvatarMediaId(erpUserInfo.getAvatarMediaId());
                    wxCpUser.setTelephone(erpUserInfo.getTelephone());
                    wxCpUser.setExternalAttrs(erpUserInfo.getExternalAttrs());
                    wxCpUser.setEnglishName(erpUserInfo.getEnglishName());
                    wxCpUser.setQrCode(erpUserInfo.getQrCode());
                    
                    wxCpService.getUserService().update(wxCpUser); // 更新存在的用户
                    //更新用户头像  
                    String avatarMediaIDUri = wxUserInfo.getAvatar();  //获取微信图像 uri    
                    if (avatarMediaIDUri != null && !"".equals(avatarMediaIDUri)) {
                        String filePath = request.getServletContext().getRealPath("/") + "uploads"+File.separator+"smallpic"+File.separator ;
                        String fileName = filePath + RandomString.getRandomString(4) +".jpg";
                        File file = AvatarFile.getAvatarFile (avatarMediaIDUri,fileName,filePath) ;  //获取微信图像 File 对象
                        if (file != null) {
                            messagesIfc.saveSubscribeEvent(wxUserInfo,corpEntity,file) ;  //上传图像文件至数据库
                        }
                    }
                }
            } catch (WxErrorException e) {
                String errmsg = "同步用户【"+erpUserInfo.getUserId()+"】【" + erpUserInfo.getName() + "】信息时有错误发生,错误代码:" + e.getError().getErrorCode()+",错误信息:" + e.getError().getErrorMsg();
                errList.add(errmsg);
                e.printStackTrace();
            }catch (Exception e) {
                errList.add("同步用户信息时有错误发生,错误代码:" +(e.getCause()!=null?e.getCause().getMessage(): e.getMessage()));
            }
        }
        
        //2.新增新用户到微信服务器 
        for (int i = 0; erpUserInfoList != null && i < erpUserInfoList.size(); i++) {
            MyWxCpUser erpUserInfo = erpUserInfoList.get(i);
            
            //如果性别为空 或 mobile/weixinid/email 同时为空,则跳过去
            if (erpUserInfo.getGender() == null || "".equals(erpUserInfo.getGender().getCode()) ||
                    ((erpUserInfo.getEmail() == null || "".equals(erpUserInfo.getEmail())) 
                    && (erpUserInfo.getMobile() == null || "".equals(erpUserInfo.getMobile())) 
                    && (erpUserInfo.getTelephone() == null || "".equals(erpUserInfo.getTelephone()))))
                    continue ;
 
            // weiXinUserStatus : 关注状态: 1=已关注,2=已冻结,4=未关注
 
            boolean isWxUserExists = false ;
            WxCpUser wxUserInfo = null ; 
            try {
                wxUserInfo = wxCpService.getUserService().getById(erpUserInfo.getUserId()) ;
                isWxUserExists = true ;
            } catch (WxErrorException e) {
                //60111  UserID不存在
                if (e.getError().getErrorCode() == 60111)  isWxUserExists = false ;
                else {
                    errList.add("获取微信用户【" + erpUserInfo.getUserId() + "】【"
                            + erpUserInfo.getName() + "】时出错,错误代码:"
                            + e.getError().getErrorCode()
                            + ",错误信息:" + e.getError().getErrorMsg()
                            + "\n");
                    e.printStackTrace();
                }
            }catch (Exception e) {
                e.printStackTrace();
                errList.add("同步用户信息时有错误发生,错误代码:" + (e.getCause()!=null?e.getCause().getMessage():e.getMessage()));
            }
            
            try {
                if ( wxUserInfo == null || !isWxUserExists  ) {
                    
                    //上传头像
                    if (erpUserInfo.getAvatarUnid()!= null && !"".equals(erpUserInfo.getAvatarUnid())) {
                        OtherMatEntity otherMatEntity = materialIfc.getAttachment(erpUserInfo.getAvatarUnid());
                        String mediaType = "image" ;
                        mediaType = WeiXinMediaType.getMediaTypeByFileType(otherMatEntity.getFileType());
                        if (otherMatEntity!=null&&otherMatEntity.getOriginalPicture()!=null) {
                            InputStream is = new ByteArrayInputStream(otherMatEntity.getOriginalPicture());
                            WxMediaUploadResult res = wxCpService.getMediaService().upload(mediaType, otherMatEntity.getFileType(), is);  //临时素材 
                            if (res.getMediaId() != null && !"".equals(res.getMediaId())) {
                                erpUserInfo.setAvatarMediaid(res.getMediaId());
                            }
                        }
                    }
                    
                    wxCpService.getUserService().create(erpUserInfo); // 新用户
                    erpUserIfc.saveWorkAppUserStatus(erpUserInfo.getUserId(), 4); // 改为: 未关注
                    //wxCpService.invite(erpUserInfo.getUserId(), "1") ;   //邀请成员关注, 此功能在“企业微信”中不能使用
                } 
 
            } catch (WxErrorException e) {
                String errmsg = "新增用户【" + erpUserInfo.getUserId() + "】【"
                        + erpUserInfo.getName() + "】时出错,错误代码:"
                        + e.getError().getErrorCode()+ ",错误信息:" + e.getError().getErrorMsg()    + "\n";
                errList.add(errmsg);
                
                e.printStackTrace();
            }catch (Exception e) {
                e.printStackTrace();
                errList.add("同步用户信息时有错误发生,错误代码:" + (e.getCause()!=null?e.getCause().getMessage(): e.getMessage()));
            }
        }  // end for
 
        // 3.删除微信服务器上的用户,而ERP系统中不存在的用户,达到同步的目的
        List<WxCpDepart> groupList = null;
        try {
            groupList = wxCpService.getDepartmentService().list(null);
        } catch (WxErrorException e) {
            String errmsg = "获取部门信息时失败,错误代码:" + e.getError().getErrorCode()
                    + ",错误信息:" + e.getError().getErrorMsg()+ "\n";
            errList.add(errmsg);
            
            e.printStackTrace();
        }catch (Exception e ) {
            e.printStackTrace();
            errList.add("获取部门信息时失败,错误代码:" + (e.getCause()!=null?e.getCause().getMessage(): e.getMessage()));
        }
 
        for (int i = 0; groupList != null && i < groupList.size(); i++) {
            WxCpDepart dept = groupList.get(i);
            List<WxCpUser> userList = null;
            try {
                userList = wxCpService.getUserService().listByDepartment(dept.getId(), false,0);
            } catch (WxErrorException e) {
                errList.add("获取【" + dept.getName()    + "】部门下的用户信息时失败,错误代码:"
                        + e.getError().getErrorCode()+ ",错误信息:"
                        + e.getError().getErrorMsg());
                e.printStackTrace();
            }catch (Exception e) {
                e.printStackTrace();
                errList.add("同步用户信息时有错误发生,错误代码:" + (e.getCause()!=null?e.getCause().getMessage():e.getMessage()));
                
            }
 
            for (int j = 0; userList != null && j < userList.size(); j++) {
                WxCpUser wxCpUser = userList.get(j);
                try {
                    boolean isFound = isExistsMyERPUser(erpUserInfoList, wxCpUser.getUserId());
                    if (!isFound) {
                        wxCpService.getUserService().delete(wxCpUser.getUserId());
                    }
                } catch (WxErrorException e) {
                    errList.add("删除【" + dept.getName() + "】部门下的用户【" + wxCpUser.getUserId() + "】【"
                            + wxCpUser.getName() + "】时失败,错误代码:" + e.getError().getErrorCode() + ",错误信息:"
                            + e.getError().getErrorMsg());
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                    errList.add("同步用户信息时有错误发生,错误代码:" + (e.getCause()!=null?e.getCause().getMessage(): e.getMessage()));
                    
                }
            } // end for
 
 
        }
 
 
        return errList;
    }
 
    /**
     * 往微信服务端写入新用户 , 主要用于 导购 网店版页面注册新用户时,同时写入微信服务端
     * @param response
     */
    public boolean newUser(HttpServletResponse response,String userCode,String userName,WxCpService wxCpService) {
        WxCpUser erpUserInfo = null;
        try {
            SpObserver.setDBtoInstance("_"+corpEntity.getDbId());
            erpUserInfo = erpUserIfc.getWorkAppUser(userCode);
        }finally {
            SpObserver.setDBtoInstance();
        }
        if (erpUserInfo == null) return false;
        
        WxCpUser wxUserInfo = null ;
        boolean isWxUserExists = false ;
        try {
            wxUserInfo = wxCpService.getUserService().getById(userCode) ;
            if (wxUserInfo != null) isWxUserExists = true ;
        } catch (WxErrorException e) {
            //60111  UserID不存在
            if (e.getError().getErrorCode() == 60111)  isWxUserExists = false ;
            else {
                System.out.println("获取微信用户【" + userCode + "】【"
                            + userName + "】时出错,错误代码:"
                            + e.getError().getErrorCode()
                            + ",错误信息:" + e.getError().getErrorMsg()
                            + "\n");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (erpUserInfo != null && ! isWxUserExists) {
                wxCpService.getUserService().create(erpUserInfo); // 新用户
                //wxCpService.invite(erpUserInfo.getUserId(),null) ;  //邀请成员关注
            }
        } catch (WxErrorException e) {
            String msg = "新增用户【" + erpUserInfo.getUserId() + "】【"
                    + erpUserInfo.getName() + "】时出错,错误代码:"
                    + e.getError().getErrorCode()
                    + ",错误信息:" + e.getError().getErrorMsg()
                    + "\n" ;
            System.out.println(msg);
            
        }catch (Exception e) {
            e.printStackTrace();
        }
        return true ; 
    }
    
    /**
     * 检查是否存在ERP用户
     * @param erpUserInfoList
     * @param userCode
     * @return
     */
    private boolean isExistsERPUser(List<WxCpUser> erpUserInfoList,String userCode) {
        if (erpUserInfoList != null) {
            for (int i = 0; i < erpUserInfoList.size(); i++) {
                WxCpUser erpUserInfo = erpUserInfoList.get(i);
                if (userCode != null && erpUserInfo.getUserId().equals(userCode)) return true ;
            }
        }
        return false ;
    }
    
    private boolean isExistsMyERPUser(List<MyWxCpUser> erpUserInfoList,String userCode) {
        if (erpUserInfoList != null) {
            for (int i = 0; i < erpUserInfoList.size(); i++) {
                WxCpUser erpUserInfo = erpUserInfoList.get(i);
                if (userCode != null && erpUserInfo.getUserId().equals(userCode)) return true ;
            }
        }
        return false ;
    }
 
    @RequestMapping("/shopping/getWorkAppUser.do")
    public void getWorkAppUser(HttpServletResponse response,HttpServletRequest request) {
        //HttpSession session = request.getSession();
        //String dbId = (String) session.getAttribute(SessionKey.SHOPPING_DBID);
        //String hostUrl = SettingKey.getHostUrl(request) ;
 
        
        JsonObject json = new JsonObject();
        JsonObject errJson = new JsonObject();
        
 
        DataSourceEntity corpEntity = null ;
        try {
            corpEntity = MultiDataSource.getDataSourceMap( request) ;
            if (corpEntity == null  ) {
                errJson.addProperty("warning", "没有找到数据源");
                json.add("error", errJson);
                this.printJson(response, json.toString());
                return;    
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        }
        
        String userId = request.getParameter("card_userid") ;
 
        try {
            SpObserver.setDBtoInstance("_"+corpEntity.getDbId());//切换数据源
            MyWxCpUser user = erpUserIfc.getWorkAppUser(userId) ;
            if (user == null) {
                errJson.addProperty("warning", "没有找到用户 userid:"+userId);
                json.add("error", errJson);
                this.printJson(response, json.toString());
                return;    
            }
            json.addProperty("card_userid", userId);
            json.addProperty("card_hrcode", user.getHrCode());
            json.addProperty("card_name", user.getName());
            json.addProperty("card_gender", user.getGender().getCode());
            json.addProperty("card_position", user.getPosition());
            json.addProperty("card_tel", user.getMobile());
            json.addProperty("card_show_tel", user.getTelephone());
            String departNamesStr = user.getDepartNames() ;
            String departNames[] = null ;
            if (departNamesStr != null && !"".equals(departNamesStr)) {
                departNames = departNamesStr.split(";") ;
            }
            JsonArray subImageListArray = new JsonArray();
            for(int i = 0 ;user.getDepartIds()!=null&&i<user.getDepartIds().length;i++) {
                JsonObject departItem = new JsonObject();
                departItem.addProperty("departid", user.getDepartIds()[i]);
                departItem.addProperty("departname", departNames !=null&& i< departNames.length?departNames[i]:"");
                subImageListArray.add(departItem);
            }
            json.add("card_departids", subImageListArray);
            
            this.printJson(response, json.toString());
            return;
        }catch (DataAccessException e) {
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        } catch (Exception e) {
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    @RequestMapping("/shopping/getMiniAppQrCode.do")
    public void getMiniAppQrCode(HttpServletResponse response,HttpServletRequest request) {
        //HttpSession session = request.getSession();
        //String dbId = (String) session.getAttribute(SessionKey.SHOPPING_DBID);
        //String hostUrl = SettingKey.getHostUrl(request) ;
 
        
        JsonObject json = new JsonObject();
        JsonObject errJson = new JsonObject();
        
        
        DataSourceEntity corpEntity = null ;
        try {
            corpEntity = MultiDataSource.getDataSourceMap( request) ;
            if (corpEntity == null  ) {
                errJson.addProperty("warning", "没有找到数据源");
                json.add("error", errJson);
                this.printJson(response, json.toString());
                return;    
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        }
        
        
        //将微信corpid组装成url
        String wxQueryString = SettingKey.getQueryStringByWx(request);
 
        String userid = request.getParameter("userid");
        if (userid==null) {
            errJson.addProperty("warning", "必须传递 userid 参数");
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;    
        }
        
        String isRefresh = request.getParameter("isrefresh") ;
        //第三方托管方式写法 
        WxMaService wxService = null;
        try {
            wxService = MaServiceInit.getWxMaServiceByOpenComponentByAppId(corpEntity.getMiniAppId()) ;
        }catch (Exception e) {
            e.printStackTrace();
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        }
        try {
            SpObserver.setDBtoInstance("_"+corpEntity.getDbId());//切换数据源
            SettingEntity settingEntity = settingIfc.getSettingEntity(request) ;
            //获取小程序二维码
            MyWxCpUser myWxCpUser = erpUserIfc.getWorkAppUser(userid) ;
            
            
            //刷新小程序二维码 
            if ((myWxCpUser!=null && ( myWxCpUser.getMiniAppQrCode() ==null || "".equals(myWxCpUser.getMiniAppQrCode()) )) || (isRefresh!=null && "true".equals(isRefresh))) {
                File miniAppQrCodeFile = null ;
                String page = ""; ;
                try {
                    
                    MaSettingEntity maSettingEntity = maSettingIfc.getMaSettingEntity() ;
                    String scene=SettingKey.FROMUSERID+"="+userid ;  
                    //String page = "pages/index/index";   //扫码时打开 小程序 商城首页
                    page = (maSettingEntity !=null&&!"".equals(maSettingEntity.getDefaultPathUrl())?maSettingEntity.getDefaultPathUrl(): "pages/index/index");   //扫码时打开 小程序 商城首页
                    int width = 430;
                    boolean autoColor = false ;
                    WxMaCodeLineColor lineColor = new  WxMaCodeLineColor("0","0","0") ;
                    boolean isHyaline = false ;
 
                    //MiniProgramState: developer  开发版 , trial 体验版 , formal 正式版
                    if (settingEntity.getMiniProgramState()!=null && settingEntity.getMiniProgramState().equals("trial") 
                            //&& (myWxCpUser==null || myWxCpUser.getMiniAppTrialQrCode()==null || "".equals(myWxCpUser.getMiniAppTrialQrCode()))
                            ) {
                        byte[] bytes = wxService.getCodeService().getQrCode(page+"?"+ scene);
                        String unid=UUID.randomUUID().toString().toUpperCase();//生成uuid
                        AttachmentWhereEntity attachmentWhereEntity= attachmentIfc.saveAttachment(unid, 700107, bytes,userid, "jpg","1") ;
                        erpUserIfc.saveMiniAppTrialQrCode(userid,attachmentWhereEntity.getUnid(),attachmentWhereEntity.getSeq()) ;
                        //File tempFile = File.createTempFile("trial", "jpg");
                        //miniAppQrCodeFile = BlobToFile.writeBytesToFile(bytes, tempFile.getPath()) ;  //将流写入文件
                    } 
                    
                    miniAppQrCodeFile = wxService.getQrcodeService().createWxaCodeUnlimit(scene, page,  width, autoColor, lineColor, isHyaline);
                    //File miniAppQrCodeFile= new File("/Users/johnswang/Downloads/小程序二维码.jpeg") ;  //testing ...
                    erpUserIfc.saveMiniAppQrCode(userid,corpEntity,miniAppQrCodeFile) ;
                
                    //重新再取一次数 
                    myWxCpUser = erpUserIfc.getWorkAppUser(userid) ;
                }catch (WxErrorException e ) {
                    e.printStackTrace();
                    if (e.getError().getErrorCode() == 41030) {
                        json.addProperty("state", "找不到小程序页面【" + page + "】, 请检查是否为该小程序上传了代码?[原始错误报文:" + e.getError().getJson()+"]" );
                    }else {
                        json.addProperty("state", e.getError().getErrorMsg()+"[原始错误报文:" + e.getError().getJson()+"]"  );
                    }
                    this.printJson(response, json.toString());
                    return;    
                }catch(Exception e) {
                    e.printStackTrace();
                    errJson.addProperty("warning",e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
                    json.add("error", errJson);
                    this.printJson(response, json.toString());
                    return;
                }finally{
                    if (miniAppQrCodeFile != null && miniAppQrCodeFile.exists()&&miniAppQrCodeFile.isFile()) {
                        log.info("del>>userCode:"+request.getSession().getAttribute(SessionKey.USERCODE)+"|dbid:"+request.getSession().getAttribute(SessionKey.DATA_BASE_ID)+"|"+miniAppQrCodeFile.getAbsolutePath());
                        miniAppQrCodeFile.delete();
                    }
                }
            }
            
            
                    
            if (myWxCpUser!=null && myWxCpUser.getMiniAppQrCode() != null && !"".equals(myWxCpUser.getMiniAppQrCode())) {
                String imgUrl = imgData.getImageUrl(myWxCpUser.getMiniAppQrCode(),settingEntity.getImagePopupWidth(),settingEntity.getImagePopupHeight(),settingEntity.isShowPopupOrgImage(),settingEntity.isFromCached(),request)  + (wxQueryString == null||"".equals(wxQueryString)?"":"?" + wxQueryString)  ;
                json.addProperty("imgurl", imgUrl);
                json.addProperty("state", "success");
            }else {
                json.addProperty("state", "请点击刷新按钮获取二维码");
            }
            this.printJson(response, json.toString());
            return;
        }catch (DataAccessException e) {
            e.printStackTrace();
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        } catch (Exception e) {
            e.printStackTrace();
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
 
    @RequestMapping("/shopping/updateWorkAppRadarUserStatus.do")
    public void updateWorkAppRadarUserStatus(HttpServletResponse response,HttpServletRequest request) {
        //HttpSession session = request.getSession();
        //String dbId = (String) session.getAttribute(SessionKey.SHOPPING_DBID);
        //String hostUrl = SettingKey.getHostUrl(request) ;
        String appCode = "addressbook" ;
        
        
        JsonObject json = new JsonObject();
        JsonObject errJson = new JsonObject();
        
        
        
 
        DataSourceEntity corpEntity = null ;
        try {
            corpEntity = MultiDataSource.getDataSourceMap( request) ;
            if (corpEntity == null  ) {
                errJson.addProperty("warning", "没有找到数据源");
                json.add("error", errJson);
                this.printJson(response, json.toString());
                return;    
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        }
        
        
        // isAiRadarUser : 0 ai雷达 , 1 boss 雷达 , 2 缺省ai雷达用户 
        String isAiRadarUser = request.getParameter("isAiRadarUser") ;
        if (isAiRadarUser==null) {
            errJson.addProperty("warning", "必须传递 isAiRadarUser 参数");
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;    
        }
        
        String isChecked = request.getParameter("isChecked") ;
        if (isChecked==null) {
            errJson.addProperty("warning", "必须传递 isSelected 参数");
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;    
        }
        
        String userid = request.getParameter("userid");
        if (userid==null) {
            errJson.addProperty("warning", "必须传递 userid 参数");
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;    
        }
        
        try {
            SuiteComponentAppEntity suiteComponentAppEntity = CpServiceInit.getSuiteComponentAppEntityFromERP(corpEntity.getCorpId(),appCode) ;
            
            SpObserver.setDBtoInstance("_"+corpEntity.getDbId());//切换数据源
            
            // isAiRadarUser : 0 ai雷达 , 1 boss 雷达 , 2 缺省ai雷达用户 
            Integer authorizedUsers = erpUserIfc.getWorkAppAuthorizedUsers(isAiRadarUser!=null&&("0".equals(isAiRadarUser)||"2".equals(isAiRadarUser))?true:false) ;
            if (isAiRadarUser!=null&&("0".equals(isAiRadarUser)||"1".equals(isAiRadarUser)) && isChecked!=null&&"true".equals(isChecked)) {
                if (authorizedUsers!=null && suiteComponentAppEntity != null 
                        && suiteComponentAppEntity.getAuthorizedUsers()!=null
                        && authorizedUsers.intValue() + 1 > suiteComponentAppEntity.getAuthorizedUsers().intValue()) {
                    errJson.addProperty("warning", "已经超出授权用户数"+suiteComponentAppEntity.getAuthorizedUsers() +",设置失败!" );
                    json.add("error", errJson);
                    this.printJson(response, json.toString());
                    return;    
                }
            }
        }catch (DataAccessException e) {
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        } catch (Exception e) {
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        } finally {
            SpObserver.setDBtoInstance();
        }
        
        try {
            SpObserver.setDBtoInstance("_"+corpEntity.getDbId());//切换数据源
            Integer ret = null ;
            if (isAiRadarUser!=null&&"0".equals(isAiRadarUser)) {   //ai 雷达
                ret = erpUserIfc.saveAiRadarUser( userid, isChecked!=null&&"true".equals(isChecked)?true:false) ;
            }
            if (isAiRadarUser!=null&&"1".equals(isAiRadarUser)) {  //boss 雷达 
                ret = erpUserIfc.saveBossRadarUser( userid, isChecked!=null&&"true".equals(isChecked)?true:false) ;
            }
            if (isAiRadarUser!=null&&"2".equals(isAiRadarUser)) {  //缺省 ai 雷达 
                ret = erpUserIfc.saveAiRadarUserForDefault( userid, isChecked!=null&&"true".equals(isChecked)?true:false) ;
            }
            
            if (ret != null && ret.equals(1)) {
                json.addProperty("state", "success");
            }else {
                errJson.addProperty("warning", "更新失败");
                json.add("error", errJson);
            }
            json.addProperty("state", "success");
            this.printJson(response, json.toString());
            return;
        }catch (DataAccessException e) {
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        } catch (Exception e) {
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
    
    @RequestMapping("/shopping/delWorkAppUser.do")
    public void delWorkAppUser(HttpServletResponse response,HttpServletRequest request) {
        //HttpSession session = request.getSession();
        //String dbId = (String) session.getAttribute(SessionKey.SHOPPING_DBID);
        //String hostUrl = SettingKey.getHostUrl(request) ;
 
        
        JsonObject json = new JsonObject();
        JsonObject errJson = new JsonObject();
        
    
        
 
        DataSourceEntity corpEntity = null ;
        try {
            corpEntity = MultiDataSource.getDataSourceMap( request) ;
            if (corpEntity == null  ) {
                errJson.addProperty("warning", "没有找到数据源");
                json.add("error", errJson);
                this.printJson(response, json.toString());
                return;    
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        }
        try {
            SpObserver.setDBtoInstance("_"+corpEntity.getDbId());//切换数据源
            List<String> userIds = new ArrayList<String>() ;
            
            Enumeration<String> enu=request.getParameterNames();  
            while(enu.hasMoreElements()){  
                String paraName=(String)enu.nextElement();  
                if(paraName.startsWith("userids")){
                    String userid = request.getParameter(paraName);
                    userIds.add(userid)  ;
                }
            }
            
            for (int i =0 ;userIds !=null && i < userIds.size();i++) {
                erpUserIfc.deleteWorkAppUser(userIds.get(i)) ;
            }
            
            
            json.addProperty("state", "success");
            this.printJson(response, json.toString());
            return;
        }catch (DataAccessException e) {
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        } catch (Exception e) {
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
    
    @RequestMapping("/shopping/saveWorkAppUser.do")
    public void saveWorkAppUser(HttpServletResponse response,HttpServletRequest request) {
        //HttpSession session = request.getSession();
        //String dbId = (String) session.getAttribute(SessionKey.SHOPPING_DBID);
        //String hostUrl = SettingKey.getHostUrl(request) ;
 
        JsonObject json = new JsonObject();
        JsonObject errJson = new JsonObject();
        
 
        DataSourceEntity corpEntity = null ;
        try {
            corpEntity = MultiDataSource.getDataSourceMap( request) ;
            if (corpEntity == null  ) {
                errJson.addProperty("warning", "没有找到数据源");
                json.add("error", errJson);
                this.printJson(response, json.toString());
                return;    
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            errJson.addProperty("warning", e.getCause()!=null?e.getCause().getMessage(): e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        }
        
        String userId = request.getParameter("card_userid") ;
        String cardHrCode = request.getParameter("card_hrcode") ;
        String cardName = request.getParameter("card_name") ;
        String cardGender = request.getParameter("card_gender") ;
        String cardPosition = request.getParameter("card_position") ;
        String cardTel = request.getParameter("card_tel") ;
        String cardShowTel = request.getParameter("card_show_tel") ;
        String cardDepartIdsStr = request.getParameter("card_departids") ;
        Long[] departIds = null ;
        if (cardDepartIdsStr !=null && !"".equals(cardDepartIdsStr)) {
            String cardDepartIdsList[] = cardDepartIdsStr.split(";") ;
            departIds = new Long[cardDepartIdsList.length] ;
            for(int i = 0 ;i < cardDepartIdsList.length;i++) {
                departIds[i] = Long.parseLong(cardDepartIdsList[i]);  
            }
        }
        
        /*
        List<Integer> departIdsList = new ArrayList<Integer>() ;
        Enumeration<String> enu=request.getParameterNames();  
        while(enu.hasMoreElements()){  
            String paraName=(String)enu.nextElement();  
            if(paraName.startsWith("departids") && paraName.contains("[departid]")){
                String departId = request.getParameter(paraName);
                departIdsList.add(Integer.parseInt(departId))  ;
            }
        }
        
        Integer[] departIds = null ;
        if (departIdsList !=null && departIdsList.size() > 0) {
            departIds = new Integer[departIdsList.size()] ;
            for(int i = 0 ;i < departIdsList.size();i++) {
                departIds[i] = departIdsList.get(i);  
            }
        }*/
        
        if (cardName == null || "".equals(cardName)) {
            errJson.addProperty("card_name", "姓名 必须输入!");
        }
        if (cardGender == null || "".equals(cardGender)) {
            errJson.addProperty("card_gender", "性别 必须输入!");
        }
        if (cardPosition == null || "".equals(cardPosition)) {
            errJson.addProperty("card_position", "职位 必须输入!");
        }
        if (cardTel == null || "".equals(cardTel)) {
            errJson.addProperty("card_tel", "绑定微信手机号 必须输入!");
        }
        if (cardShowTel == null || "".equals(cardShowTel)) {
            errJson.addProperty("card_show_tel", "名片展示手机号 必须输入!");
        }
        if (departIds == null || departIds.length == 0) {
            errJson.addProperty("departids", "部门 必须输入!");
        }
        
        Set<Entry<String, JsonElement>> it = errJson.entrySet();
        if (!it.isEmpty() && it.size() != 0) {
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        }
        
        
        try {
            SpObserver.setDBtoInstance("_"+corpEntity.getDbId());//切换数据源
            
            
            
            WxCpUser wxCpUser = new WxCpUser() ;
            if (userId == null || "".equals(userId)) {
                userId = PinyinRec.spell(cardName) ;
            }
            wxCpUser.setUserId(userId);
            wxCpUser.setName(cardName);
            if (cardGender !=null && "1".equals(cardGender)) {
                wxCpUser.setGender(Gender.MALE);
            } else {
                wxCpUser.setGender(Gender.FEMALE);
            }
            wxCpUser.setPosition(cardPosition);
            wxCpUser.setMobile(cardTel);
            wxCpUser.setTelephone(cardShowTel);
            wxCpUser.setDepartIds(departIds);
            
            erpUserIfc.saveWorkAppUser(wxCpUser,cardHrCode) ;
            //System.out.println(this.getClass()+" saveUserInfoResultEntity:" + saveUserInfoResultEntity.getAffectedRows());
            json.addProperty("state", "success");
            this.printJson(response, json.toString());
            return;
        }catch (DataAccessException e) {
            errJson.addProperty("warning", e.getCause().getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        } catch (Exception e) {
            errJson.addProperty("warning", e.getMessage());
            json.add("error", errJson);
            this.printJson(response, json.toString());
            return;
        } finally {
            SpObserver.setDBtoInstance();
        }
    }
}