fs-danaus
2023-06-26 2e5389660d216dabf6ebee15e7a3fa6eab73d01d
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
package com.yc.listener;
 
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
 
import com.alibaba.fastjson.JSON;
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.shopping.action.api.InvitationCode;
import org.apache.catalina.Manager;
import org.apache.catalina.Session;
import org.apache.catalina.core.ApplicationContext;
import org.apache.catalina.core.ApplicationContextFacade;
import org.apache.catalina.core.StandardContext;
 
import com.yc.action.mail.service.OtherMailIfc;
import com.yc.entity.DataSourceEntity;
import com.yc.entity.OnlineUserEntity;
import com.yc.factory.FactoryBean;
import com.yc.license.InitLicense;
import com.yc.multiData.MultiDataSource;
import com.yc.multiData.SpObserver;
import com.yc.service.user.UserAccountServiceIfc;
import com.yc.utils.SessionKey;
import org.springframework.data.redis.core.RedisTemplate;
 
/**
 *  通过sessionId 获得session
 * 自servlet2.1后就不支持httpSessionContext.get(id)所以自己实现通过sessionId 获得session
 * @author heqing.hbs@gmail.com
 * @updatedBy
 * @updateTime 2011-5-16 下午01:57:00
 */
public class SessionListener implements HttpSessionListener,Serializable{
    private static final long serialVersionUID=762508508425279327l;
    private static Map<String,HttpSession> sessions = new ConcurrentHashMap<String,HttpSession>();   //所有会话信息
    
    public static HttpSession getSession(String sessionId) {  
        if (sessionId == null) {  
            return null;  
        }  
        return sessions.get(sessionId);  
    } 
    
    /**
     * 检查当前是否已超限制人数 , 返回:true 表示超过限制人数,false 未超过
     * @param dbid
     * @return
     */
    public static boolean checkUserLimit(HttpServletRequest request,String dbid){//检查当前是否已超限制人数
        int onlineUserCount = getOnLineUserCount(request,dbid);
        DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap( dbid) ;
        return (onlineUserCount >= dataSourceEntity.getLimitUserNumber() && dataSourceEntity.getLimitUserNumber() != 0 )?true:false;
     }
    
    /**
     * 按 dbid 返回在线用户个数 
     * @param dbId
     * @return
     */
    public static int getOnLineUserCount(HttpServletRequest request,String dbId){
        int onlineUserCount = 0 ;
        try {
            Session[] sessions = getSessions(request) ;
            for (int i = 0 ; sessions != null && i < sessions.length;i++) {
            //for (Entry<String,HttpSession> entry:sessions.entrySet()) {        
            //    HttpSession session = entry.getValue(); 
                HttpSession session = sessions[i].getSession();
                if (session != null) {
                    String sessDbid = getDatabaseId(session) ;   //获取会话 session 里面的 dbid 
                    if (sessDbid == null || "".equals(dbId)) {
                        continue ;
                    }
                    String userCode = null ;
                    if (session.getAttribute(SessionKey.USERCODE) != null) {
                        userCode = (String)session.getAttribute(SessionKey.USERCODE) ;
                    }
                    if (userCode == null && session.getAttribute(SessionKey.HRCODE)!=null ) {
                        userCode = (String)session.getAttribute(SessionKey.HRCODE) ;
                    }
                    
                    
                    if (sessDbid != null && dbId != null && sessDbid.equals(dbId) && userCode != null && !"".equals(userCode)) {
                        onlineUserCount ++ ;
                    }
                }
            }
        }catch (Exception e) {
            //e.printStackTrace();
            throw e ;
        }
        
        return onlineUserCount ;
    }
    
    @Override
    public void sessionCreated(HttpSessionEvent event) {
        try {
            HttpSession session = event.getSession();
            sessions.put(session.getId(), session);        
        }catch(Exception e ) {
            e.printStackTrace();
            throw e ;
        }
    }
    
    /**
     * 返回 tomcat 真实的session集合(从 tomcat 内存中取session数 ) 
     * @param request
     * @return
     */
    public static Session[] getSessions(HttpServletRequest request) {
        try
        {
            Manager persistenceManager = getPersistenceManager( request) ;
            if (persistenceManager == null) {
                return null ;
            }
            
            Session[] sessions =  persistenceManager.findSessions();
            return sessions ;
        } catch(SecurityException e) {
            e.printStackTrace();
        } catch(IllegalArgumentException e) {
            e.printStackTrace();
        }
        
        return null ;
    }
    
    /**
     * 获取 tomcat Manager 对象,用于获取 tomcat 内存中的 session 
     * 感谢国外网友提供: https://stackoverflow.com/questions/5807664/tomcat-how-to-access-session-manager-from-servlet
     * @param request
     * @return
     */
    private static Manager getPersistenceManager(HttpServletRequest request) {
 
 
        try
        {
            Manager persistenceManager=null;
            if(request!=null) {
                ApplicationContextFacade appContextFacadeObj = (ApplicationContextFacade) request.getSession().getServletContext();
                Field applicationContextField = appContextFacadeObj.getClass().getDeclaredField("context");
                applicationContextField.setAccessible(true);
                ApplicationContext appContextObj = (ApplicationContext) applicationContextField.get(appContextFacadeObj);
                Field standardContextField = appContextObj.getClass().getDeclaredField("context");
                standardContextField.setAccessible(true);
                StandardContext standardContextObj = (StandardContext) standardContextField.get(appContextObj);
                 persistenceManager = standardContextObj.getManager();
            }else{
                org.apache.catalina.loader.WebappClassLoaderBase webappClassLoaderBase =(org.apache.catalina.loader.WebappClassLoaderBase) Thread.currentThread().getContextClassLoader();
                StandardContext standardContext = (StandardContext)webappClassLoaderBase.getResources().getContext();
                persistenceManager=standardContext.getManager();
            }
            return persistenceManager ;
        }
        catch(SecurityException e)
        {
            e.printStackTrace();
           // logger.error(e);
        }
        catch(NoSuchFieldException e)
        {
            e.printStackTrace();
           // logger.error(e);
        }
        catch(IllegalArgumentException e)
        {
            e.printStackTrace();
            //logger.error(e);
        }
        catch(IllegalAccessException e)
        {
            e.printStackTrace();
          //  logger.error(e);
        }
        return null ;
    }
    
    
    /**
     * 返回 tomcat 真实的 session (从 tomcat 内存中取session数 ) 
     * @param request
     * @return
     */
    public static HttpSession getSession(HttpServletRequest request,String sessionId) {
        try
        {
            HttpSession localSession = sessions.get(sessionId) ;
            if (localSession != null) {
                return localSession ;
            }
            
            Manager persistenceManager = getPersistenceManager( request) ;
            if (persistenceManager == null) {
                return null ;
            }
            Session session = persistenceManager.findSession(sessionId);
            return (session != null ? session.getSession():null) ;
        } catch(SecurityException e) {
            e.printStackTrace();
        }catch(IllegalArgumentException e) {
            e.printStackTrace();
        }catch (IOException e) {    
            e.printStackTrace();
        }
        return null ;
    }
    
    /**
     * 返回在线用户
     * @param dbId
     * @return
     */
    public static List<OnlineUserEntity> getOnLineUser(HttpServletRequest request,String dbId) {
        List<OnlineUserEntity> onlineUserList = null ;
        try {
            Session[] sessions = getSessions( request) ;
            //for (Entry<String,HttpSession> entry:sessions.entrySet()) {    
            //        HttpSession session = entry.getValue(); 
            for (int i = 0 ;sessions != null && i < sessions.length;i++) {
                HttpSession session = sessions[i].getSession();
                
                if (session != null) {
                    String sessDbid = getDatabaseId(session) ;   //获取会话 session 里面的 dbid 
                    if (sessDbid == null || "".equals(dbId)) {
                        continue ;
                    }
                    
                    if (sessDbid != null && dbId != null && sessDbid.equals(dbId)) {
                        String sessionId = session.getId();
                        
                        String userCode = null ;
                        if (session.getAttribute(SessionKey.USERCODE) != null) {
                            userCode = (String)session.getAttribute(SessionKey.USERCODE) ;
                        }
                        if (userCode == null && session.getAttribute(SessionKey.HRCODE)!=null ) {
                            userCode = (String)session.getAttribute(SessionKey.HRCODE) ;
                        }
                        
                        if (userCode == null || "".equals(userCode)) {
                            continue ;
                        }
                        
                        String userName = (session.getAttribute(SessionKey.USER_NAME) == null?"":(String) session.getAttribute(SessionKey.USER_NAME)) ;
                        Date loginDate = (session.getCreationTime() == 0 ? null :new Date(session.getCreationTime()) ) ;
                        
                        OnlineUserEntity onlineUserEntity = new OnlineUserEntity() ;
                        onlineUserEntity.setLoginType(Integer.parseInt(session.getAttribute(SessionKey.USER_LOGIN_TYPE)==null?"1":session.getAttribute(SessionKey.USER_LOGIN_TYPE)+""));
                        onlineUserEntity.setSessionId(sessionId).setUserCode(userCode).setUserName(userName).setLoginDate(loginDate);
                        if (onlineUserList == null) {
                            onlineUserList = new ArrayList<OnlineUserEntity>() ;
                        }
                        onlineUserList.add(onlineUserEntity);
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw e ;
        }
        return onlineUserList ;
    }
    /**
     * 删除所有在线用户
     * @param dbid
     * @return
     */
    public static void delAllOnLineUser(String dbid) {
        try {
            Session[] sessions = getSessions( null) ;
            for(Session session:sessions){
                HttpSession localSession=  session.getSession();
                String sessDbid = getDatabaseId(localSession ) ;   //获取会话 session 里面的 dbid
                if (sessDbid == null || !sessDbid.equals(dbid)) {
                    continue ;
                }
                if(localSession!=null) {
                    if (localSession.getAttribute(SessionKey.USER_LOGIN_TYPE).equals(SessionKey.USER_LOGIN_TYPE_APP)) {
                        RedisTemplate redisTemplate = (RedisTemplate) FactoryBean.getBean("redisTemplate");
                        redisTemplate.delete(InvitationCode.TOKEN_STR + localSession.getAttribute(SessionKey.DATA_BASE_ID) + ":" + localSession.getAttribute(SessionKey.USERCODE));
                    }
                    localSession.invalidate(); //删除该会话
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 删除在线用户
     * @param dbId
     * @return
     */
    public static boolean delOnLineUser(HttpServletRequest request,String sessionId) {
        boolean found = false ; 
        try {
            HttpSession localSession = sessions.get(sessionId) ;
            if (localSession!= null) {
                    //如果是APP的会话则需要把token也消除 by danaus 2020/3/16 14:55
                    if (localSession.getAttribute(SessionKey.USER_LOGIN_TYPE).equals(SessionKey.USER_LOGIN_TYPE_APP)) {
                        RedisTemplate redisTemplate = (RedisTemplate) FactoryBean.getBean("redisTemplate");
                        redisTemplate.delete(InvitationCode.TOKEN_STR + localSession.getAttribute(SessionKey.DATA_BASE_ID) + ":" + localSession.getAttribute(SessionKey.USERCODE));
                    }
                localSession.invalidate(); //删除该会话
                //removeAllSessionKey(localSession) ;
                return true ;
            }
            
            Manager persistenceManager = getPersistenceManager( request) ;
            if (persistenceManager == null) {
                return false ;
            }
            Session session = persistenceManager.findSession(sessionId);
            if (session != null) {
                session.getSession().invalidate();
                //removeAllSessionKey(localSession) ;
                return true ;
            }
            
        }catch (Exception e) {
            e.printStackTrace();
        }
        return found ;
    }
 
    /**
     * 返回所有在线用数量
     * @return
     */
    public static int getOnLineUserCount(HttpServletRequest request) {
        int count = 0 ;
        try {
            //for (Entry<String,HttpSession> entry:sessions.entrySet()) {        
            //    HttpSession session = entry.getValue(); 
            Session[] sessions = getSessions(request) ;
            for (int i = 0 ;sessions != null && i < sessions.length;i ++) {
                HttpSession session = sessions[i].getSession();    
                
                String dbId = getDatabaseId(session) ;
                if(dbId!=null&&!"".equals(dbId)){
                    
                    String userCode = null ;
                    if (session.getAttribute(SessionKey.USERCODE) != null) {
                        userCode = (String)session.getAttribute(SessionKey.USERCODE) ;
                    }
                    if (userCode == null && session.getAttribute(SessionKey.HRCODE)!=null ) {
                        userCode = (String)session.getAttribute(SessionKey.HRCODE) ;
                    }
                    
                    if (userCode == null || "".equals(userCode)) {
                        continue ;
                    }
                    count ++ ;
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw e ;
        }
        return count ;
    }    
    
    /**
     * 加载全部或条件查询系统在线人数
     * @param lookup
     * @return
     */
    public static String getLookup(HttpServletRequest request,String lookup) {
        List<Map<String, String>> listm = new ArrayList<Map<String, String>>();
        List<String> li = new ArrayList<String>();
        Map<String, Object> companyM = new HashMap<String, Object>();
        long day = 0;
        long hour = 0;
        long min = 0;
        //int count = 0;
        try {
            lookup = (lookup.equals("系统名称、域名") ? "" : lookup);
            SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm");// 设置日期格式
            long time1 = df.parse(df.format(new Date())).getTime(); // 系统当前时间
            try {
                SpObserver.setDBtoDemo();
                OtherMailIfc oterIfc = (OtherMailIfc) FactoryBean.getBean("OtherMailImpl");
                List<Map<String, Object>> companylist = oterIfc.getCompanyName();
                for (Map<String, Object> compan : companylist) {
                    companyM.put(compan.get("id").toString(), compan.get("systemID"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                SpObserver.setDBtoInstance();
            }
            
            
            //for (Entry<String,HttpSession> entry:sessions.entrySet()) {        
            //    HttpSession session = entry.getValue(); 
            Session[] sessions = getSessions(request) ;
            for (int i = 0 ;sessions != null && i < sessions.length;i ++) {
                HttpSession session = sessions[i].getSession();
                String dbId = getDatabaseId(session) ;
                
                
                if (dbId != null && !"".equals(dbId)) {
                    try {
                        String userCode = null ;
                        if (session.getAttribute(SessionKey.USERCODE) != null) {
                            userCode = (String)session.getAttribute(SessionKey.USERCODE) ;
                        }
                        if (userCode == null && session.getAttribute(SessionKey.HRCODE)!=null ) {
                            userCode = (String)session.getAttribute(SessionKey.HRCODE) ;
                        }
                        
                        if (userCode == null || "".equals(userCode)) {
                            continue ;
                        }
                        //count ++ ;
                        Map<String, String> lookm = new HashMap<String, String>();
                        String domain = session.getAttribute(SessionKey.DOMAIN).toString();
                        String userName = session.getAttribute(SessionKey.USER_NAME).toString();
                        String dbid = session.getAttribute(SessionKey.DATA_BASE_ID).toString();
                        String company = (String) companyM.get(dbid);
                        if (company.toLowerCase().indexOf(lookup.toLowerCase()) != -1
                                || domain.toLowerCase().indexOf(lookup.toLowerCase()) != -1 || lookup.equals("")
                                || lookup.equals(null)) {
                            long time2 = df.parse(df.format(new Date(session.getCreationTime()))).getTime();
                            long diff = time1 - time2;
                            day = diff / (24 * 60 * 60 * 1000);
                            hour = (diff / (60 * 60 * 1000) - day * 24);
                            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
                            String longtime = (hour > 0 ? hour + "时" + min + "分钟" : min + "分钟");
                            lookm.put(dbid,
                                    company + ";" + domain + ";" + userName + ";"
                                            + df.format(new Date(session.getCreationTime())) + ";" + longtime + ";"
                                            + session.getId());
                            listm.add(lookm);
                            li.add(dbid);
                        }
                    } catch (Exception e) {
                        continue;
                    }            
                    
                }
            
            
            }
            
            HashSet<String> hs = new HashSet<String>(li);
            return  listm.size()+"@"+gethtml(hs, listm);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            listm.clear();
            li.clear();
            companyM.clear();
        }
        return null;
    }    
 
    /**
     * 返回html里的tr内容
     * @param looklist 系统在线人数信息
     * @return
     */
    public static String gethtml(HashSet<String> li, List<Map<String, String>> listm) {
        String inner = "";
        try {
            int ac = 1;
            for (String dbid : li) {
                inner += "<dt><a href=\"#accordion" + ac + "\" aria-expanded=\"false\" aria-controls=\"accordion" + ac
                        + "\" " + "class=\"accordion-title accordionTitle js-accordionTrigger\">[#title]"
                                + "<font size=\"1\"> ([#cont])</font></a></dt>"
                        + "<dd class=\"accordion-content accordionItem is-collapsed\" id=\"accordion" + ac
                        + "\" aria-hidden=\"true\">"
                        + "<ul class=\"menu\"><li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;域名</li>"
                        + "<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;用户</li>"
                        + "<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;登录时间</li>"
                        + "<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;在线时长</li>"
                        + "<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
                        + "&nbsp;&nbsp;&nbsp;操作</li>" + "</ul><br><hr>";
                ac++;
                int cont = 0;
                for (Map<String, String> keymap : listm) {
                    if (keymap.get(dbid) == null) {
                        continue;
                    }
                    cont++;
                    inner += "<ul class=\"menus\">";
                    String[] columns = keymap.get(dbid).toString().split(";");
                    inner = inner.replace("[#title]", columns[0]);
                    for (int j = 1; j < columns.length; j++)
                        if (j == columns.length - 1) {
                            inner += "<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
                                    + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[<a href=\"javascript:delOnlineUser('"
                                    + columns[5] + "');\">踢除</a>]</li>";
                        } else {
                            if (j > 1) {
                                inner += "<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + columns[j] + "</li>";
                            } else {
                                inner += "<li>" + columns[j] + "</li>";
                            }
 
                        }
                    inner += "</ul><br><hr>";
                }
                inner = inner.replace("[#cont]", cont+"个用户在线");
                inner += "</br><ul class=\"menus\"><li>小计:" + cont + "个用户在线</li></ul>";
                inner += "</dd>";
            }
        } catch (Exception e) {
            return inner;
        }
        return inner;
    }    
    
    /**
     * 10天在线人数统计
     * @param looktenday 时间段
     * @return
     */    
    @SuppressWarnings("static-access")
    public static String getTendays(String lookTenDay, int conts) throws SQLException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String inthtml = "";
        try {
            Date start = null;
            Date end = null;
            Calendar rightNow = Calendar.getInstance();
            if (lookTenDay.equals("today")) {
                Date nowDate = new Date();
                rightNow.setTime(nowDate);
                rightNow.add(rightNow.DATE, -9);
                start = rightNow.getTime();
                end = nowDate;
            } else {
                end = df.parse(lookTenDay);
                rightNow.setTime(end);
                rightNow.add(rightNow.DATE, -9);
                start = rightNow.getTime();
            }
            try {
                OtherMailIfc oterIfc = (OtherMailIfc) FactoryBean.getBean("OtherMailImpl");
                List<Map<String, Object>> idlist = null;
                int count = 0;
                try {
                    SpObserver.setDBtoDemo();
                    idlist = oterIfc.getOnBusDBSourseID(conts);
                    count = oterIfc.getCountDBSourseID();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    SpObserver.setDBtoInstance();
                }
                UserAccountServiceIfc userAccountServiceIfc = (UserAccountServiceIfc) FactoryBean
                        .getBean("UserAccountServiceImpl");
                //String htmltxt = "";
                Map<String, Integer> contMap = new HashMap<String, Integer>();// 计算在线人数总和
                                                                                // 集合
                for (Map<String, Object> m : idlist) {
                    try {
                        SpObserver.setDBtoInstance("_" + m.get("id").toString());
                        List<Map<String, String>> list = userAccountServiceIfc.StatisticUserLoginByDay(start, end);
                        if (list != null) {// 如果没有则关闭
                            inthtml += getTenhtml(inthtml, (String) m.get("systemID"), contMap, list); // 返回10天统计html里的tr内容
                        }
                    } catch (Exception e2) {
                        if (!e2.getLocalizedMessage().equals("")) {
                            System.out.print(e2.getLocalizedMessage() + "[" + m.get("bd") + "]");
                        }
                        continue;
                    } finally {
                        SpObserver.setDBtoInstance();
                    }
                }
                // 返回组装好的tr标签
                inthtml = inthtml + getConts(count, contMap);
            } catch (Exception e) {
                return e.getCause().getMessage();
            }
        } catch (Exception e1) {
            return e1.getCause().getMessage();
        }
        return inthtml;
    }
    
    
    /**
     * 返回10天统计html里的tr内容
     * @param inthtml 显示栏
     * @param systemID 每一个系统名称
     * @param contMap 计算在线人数总数
     * @param listhtml tr标签内容
     * @return
     */
    public static String getTenhtml(String inthtml,String systemID,Map<String, Integer> contMap,List<Map<String,String>> listhtml){
        String inner="";
        String dbtxt="";
        int conts=0;
        try {        
                 inner+="<tr align=\"center\" class=\"adadad\"><td>系统名称</td>";
                 dbtxt+="<tr align=\"center\" class=\"conts\"><td>"+systemID+"</td>";
                         for (int i = 0; i < listhtml.size(); i++) {
                             inner+="<td>"+listhtml.get(i).get("dt")+"</td>";
                             dbtxt+="<td>"+listhtml.get(i).get("counts")+"</td>";
                             conts+=Integer.parseInt(listhtml.get(i).get("counts"));
                             contMap.put(listhtml.get(i).get("id"), 
                                     (Integer) (contMap.get(listhtml.get(i).get("id"))==null?
                                     Integer.parseInt(listhtml.get(i).get("counts")):
                                     (contMap.get(listhtml.get(i).get("id"))+Integer.parseInt(listhtml.get(i).get("counts")))));
                        }
                         inner+="<td>合计</td></tr>";
                         dbtxt+="<td class=\"conts\">"+conts+"</td></tr>";
                         contMap.put(String.valueOf((listhtml.size()+1)), contMap.get(String.valueOf(listhtml.size()+1))==null?
                                 conts:(contMap.get(String.valueOf(listhtml.size()+1))+conts));
            if (inthtml.equals("")) {
                dbtxt=inner+dbtxt;
            }            
        } catch (Exception e) {
            return inner;
        }
        return dbtxt;
    }
    
    /**
     * 计算在线人数总和
     * @param count 页码计算
     * @param contMap 在线人数总数集合
     * @return
     */
    public static String getConts(int count,Map<String, Integer> contMap){
        String page="<tr align=\"center\" class=\"conts\"><td>合计</td>";
        try {            
            for (int i = 1; i < contMap.size()+1; i++) {
                page+="<td >"+contMap.get(String.valueOf(i))+"</td>";
            }
            page+="</tr><tr align=\"center\"><td colspan=\"12\">"
                    + "<a href=\"javascript:pagelook(1);\">第1页</a>&nbsp;&nbsp;";
            if (count>19) {
                double uble=(double)count/19;
                int number=(int) Math.ceil(uble);
                for (int i = 1; i <number ; i++) {
                    page+="<a href=\"javascript:pagelook("+19*i+");\">第"+(i+1)+"页</a>&nbsp;&nbsp;";
                   }        
            }    
        } catch (Exception e) {
            // TODO: handle exception 
            return page;
        }finally{
            contMap=null;
            count=0;
        }
        return page;
    }
    
    
    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        try {
            InitLicense.getInstance().pusSessionCount();//给加密狗用,作为单个客户计数使用
            HttpSession session = event.getSession();
            String sessionId = session.getId();
            String dbId = getDatabaseId(session) ;
            if(dbId!=null&&!"".equals(dbId)&&session.getAttribute("isClose")==null){//session.getAttribute("isClose")表示手动退出系统
                try{
                    SpObserver.setDBtoInstance("_"+dbId);
                    UserAccountServiceIfc userAccountServiceIfc = (UserAccountServiceIfc)FactoryBean.getBean("UserAccountServiceImpl");
                    userAccountServiceIfc.doQuitLog(sessionId);   //更新 _sysloginlog 日志表
                    //发送会话失效通知
                    MessageInfo messageInfo = new MessageInfo();
                    messageInfo.setDbId(Integer.parseInt(dbId));
                    messageInfo.setMsgType(MessageType.RELOGIN_PAGE);
                    messageInfo.setUserFromType(session.getAttribute(SessionKey.USER_LOGIN_TYPE)+"");
                    messageInfo.setUserCode(session.getAttribute(SessionKey.USERCODE)+"");
                    messageInfo.setSessionId(sessionId);
                    messageInfo.setMsg("您已太长时间没有操作,请重新登录");
                    WebSocketMessageServer.publishMessageToRedis(messageInfo);
                }catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    SpObserver.setDBtoInstance();
                }
            }
            sessions.remove(sessionId);
        }catch(Exception e ) {
            e.printStackTrace();
            throw e ;
        }
    }
    
//    public static HttpSession getSession(String id){
//        return sessions.get(id);
//    }
    
//    public static Map<String,HttpSession> getSessions() {
//        return sessions ;
//    }
 
    /**
     * 删除 dbid 所有会话信息
     * @param dbId
     * @return
     */
    public static int delSession(HttpServletRequest request,String dbId) {
        int count = 0 ;
        try {
            
            //for (Entry<String,HttpSession> entry:sessions.entrySet()) {        
            //    HttpSession session = entry.getValue(); 
            Session[] sessions = getSessions(request) ;
            for (int i = 0 ;sessions != null && i < sessions.length;i ++) {
                HttpSession session = sessions[i].getSession();
                //System.out.println(  "正在检查 delSession() sessionid:" + session.getId());
                if (session != null) {
                    String sessDbid = getDatabaseId(session) ;   //获取会话 session 里面的 dbid 
                    
                    if (sessDbid != null && dbId != null && sessDbid.equals(dbId)) {
                        String userCode = null ;
                        if (session.getAttribute(SessionKey.USERCODE) != null) {
                            userCode = (String)session.getAttribute(SessionKey.USERCODE) ;
                        }
                        if (userCode == null && session.getAttribute(SessionKey.HRCODE)!=null ) {
                            userCode = (String)session.getAttribute(SessionKey.HRCODE) ;
                        }
                        
                        if (userCode == null || "".equals(userCode)) {
                            continue ;
                        }
                        
                        //先不删除会话信息,因再次使用时,会导致 Session already invalidated 错误,用 removeAllSessionKey 过程代替
                        session.invalidate();   //删除会话 ,
                        
                        //removeAllSessionKey(session) ;
                        count ++ ;
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            throw e ;
        }
        return count ;
    }
    
    /**
     * 删除会话所有键值
     * @param session
     */
    public static void removeAllSessionKey (HttpSession session) {
        Enumeration<String> enumeration =session.getAttributeNames();//获取session中所有的键值对
        //遍历enumeration中的键值对
        while(enumeration.hasMoreElements()){
            String key=enumeration.nextElement().toString();//获取session中的键值
            session.removeAttribute(key);
        }
    }
    
    public static String getDatabaseId(HttpSession session) {
        String sessDbid = null ;
        if (session.getAttribute(SessionKey.DATA_BASE_ID) != null) {
            sessDbid = (String)session.getAttribute(SessionKey.DATA_BASE_ID) ;
        }
        if (sessDbid == null || "".equals(sessDbid) ) {
            sessDbid = (String)session.getAttribute(SessionKey.SHOPPING_DBID);
        }
        return sessDbid ;
    }
}