fs-danaus
2023-07-10 4849078e3450b8d3b3030a658a34dd58b0630fc5
提交 | 用户 | age
a6a76f 1 package com.yc.listener;
F 2
3 import com.yc.action.mail.service.OtherMailIfc;
4 import com.yc.entity.DataSourceEntity;
5 import com.yc.entity.OnlineUserEntity;
6 import com.yc.factory.FactoryBean;
7 import com.yc.license.InitLicense;
8 import com.yc.multiData.MultiDataSource;
9 import com.yc.multiData.SpObserver;
484907 10 import com.yc.sdk.WebSocketMessage.action.WebSocketMessageServer;
F 11 import com.yc.sdk.WebSocketMessage.entity.MessageInfo;
12 import com.yc.sdk.WebSocketMessage.entity.MessageType;
13 import com.yc.sdk.shopping.action.api.InvitationCode;
a6a76f 14 import com.yc.service.user.UserAccountServiceIfc;
484907 15 import com.yc.utils.FileUtil;
a6a76f 16 import com.yc.utils.SessionKey;
484907 17 import org.apache.catalina.Manager;
F 18 import org.apache.catalina.Session;
19 import org.apache.catalina.core.ApplicationContext;
20 import org.apache.catalina.core.ApplicationContextFacade;
21 import org.apache.catalina.core.StandardContext;
22 import org.apache.commons.io.FileUtils;
a6a76f 23 import org.springframework.data.redis.core.RedisTemplate;
484907 24
F 25 import javax.servlet.ServletContext;
26 import javax.servlet.ServletContextEvent;
27 import javax.servlet.ServletContextListener;
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpSession;
30 import javax.servlet.http.HttpSessionEvent;
31 import javax.servlet.http.HttpSessionListener;
32 import java.io.File;
33 import java.io.FileNotFoundException;
34 import java.io.IOException;
35 import java.io.Serializable;
36 import java.lang.reflect.Field;
37 import java.sql.SQLException;
38 import java.text.SimpleDateFormat;
39 import java.util.*;
40 import java.util.concurrent.ConcurrentHashMap;
a6a76f 41
F 42 /**
43  *  通过sessionId 获得session
44  * 自servlet2.1后就不支持httpSessionContext.get(id)所以自己实现通过sessionId 获得session
45  * @author heqing.hbs@gmail.com
46  * @updatedBy
47  * @updateTime 2011-5-16 下午01:57:00
48  */
484907 49 public class SessionListener implements HttpSessionListener, ServletContextListener,Serializable{
a6a76f 50     private static final long serialVersionUID=762508508425279327l;
F 51     private static Map<String,HttpSession> sessions = new ConcurrentHashMap<String,HttpSession>();   //所有会话信息
484907 52     private static  String servletContextPath;
a6a76f 53     public static HttpSession getSession(String sessionId) {  
F 54         if (sessionId == null) {  
55             return null;  
56         }  
57         return sessions.get(sessionId);  
484907 58     }
F 59
60     @Override
61     public void contextInitialized(ServletContextEvent sce) {
62         servletContextPath=sce.getServletContext().getRealPath("/");
63     }
64
a6a76f 65     /**
F 66      * 检查当前是否已超限制人数 , 返回:true 表示超过限制人数,false 未超过
67      * @param dbid
68      * @return
69      */
70     public static boolean checkUserLimit(HttpServletRequest request,String dbid){//检查当前是否已超限制人数
71         int onlineUserCount = getOnLineUserCount(request,dbid);
72         DataSourceEntity dataSourceEntity = MultiDataSource.getDataSourceMap( dbid) ;
73         return (onlineUserCount >= dataSourceEntity.getLimitUserNumber() && dataSourceEntity.getLimitUserNumber() != 0 )?true:false;
74      }
75     
76     /**
77      * 按 dbid 返回在线用户个数 
78      * @param dbId
79      * @return
80      */
81     public static int getOnLineUserCount(HttpServletRequest request,String dbId){
82         int onlineUserCount = 0 ;
83         try {
84             Session[] sessions = getSessions(request) ;
85             for (int i = 0 ; sessions != null && i < sessions.length;i++) {
86             //for (Entry<String,HttpSession> entry:sessions.entrySet()) {        
87             //    HttpSession session = entry.getValue(); 
88                 HttpSession session = sessions[i].getSession();
89                 if (session != null) {
90                     String sessDbid = getDatabaseId(session) ;   //获取会话 session 里面的 dbid 
91                     if (sessDbid == null || "".equals(dbId)) {
92                         continue ;
93                     }
94                     String userCode = null ;
95                     if (session.getAttribute(SessionKey.USERCODE) != null) {
96                         userCode = (String)session.getAttribute(SessionKey.USERCODE) ;
97                     }
98                     if (userCode == null && session.getAttribute(SessionKey.HRCODE)!=null ) {
99                         userCode = (String)session.getAttribute(SessionKey.HRCODE) ;
100                     }
101                     
102                     
103                     if (sessDbid != null && dbId != null && sessDbid.equals(dbId) && userCode != null && !"".equals(userCode)) {
104                         onlineUserCount ++ ;
105                     }
106                 }
107             }
108         }catch (Exception e) {
109             //e.printStackTrace();
110             throw e ;
111         }
112         
113         return onlineUserCount ;
114     }
115     
116     @Override
117     public void sessionCreated(HttpSessionEvent event) {
118         try {
119             HttpSession session = event.getSession();
120             sessions.put(session.getId(), session);        
121         }catch(Exception e ) {
122             e.printStackTrace();
123             throw e ;
124         }
125     }
126     
127     /**
128      * 返回 tomcat 真实的session集合(从 tomcat 内存中取session数 ) 
129      * @param request
130      * @return
131      */
132     public static Session[] getSessions(HttpServletRequest request) {
133         try
134         {
135             Manager persistenceManager = getPersistenceManager( request) ;
136             if (persistenceManager == null) {
137                 return null ;
138             }
139             
140             Session[] sessions =  persistenceManager.findSessions();
141             return sessions ;
142         } catch(SecurityException e) {
143             e.printStackTrace();
144         } catch(IllegalArgumentException e) {
145             e.printStackTrace();
146         }
147         
148         return null ;
149     }
150     
151     /**
152      * 获取 tomcat Manager 对象,用于获取 tomcat 内存中的 session 
153      * 感谢国外网友提供: https://stackoverflow.com/questions/5807664/tomcat-how-to-access-session-manager-from-servlet
154      * @param request
155      * @return
156      */
157     private static Manager getPersistenceManager(HttpServletRequest request) {
158
e98f5c 159
F 160         try
a6a76f 161         {
e98f5c 162             Manager persistenceManager=null;
F 163             if(request!=null) {
164                 ApplicationContextFacade appContextFacadeObj = (ApplicationContextFacade) request.getSession().getServletContext();
165                 Field applicationContextField = appContextFacadeObj.getClass().getDeclaredField("context");
166                 applicationContextField.setAccessible(true);
167                 ApplicationContext appContextObj = (ApplicationContext) applicationContextField.get(appContextFacadeObj);
168                 Field standardContextField = appContextObj.getClass().getDeclaredField("context");
169                 standardContextField.setAccessible(true);
170                 StandardContext standardContextObj = (StandardContext) standardContextField.get(appContextObj);
171                  persistenceManager = standardContextObj.getManager();
172             }else{
173                 org.apache.catalina.loader.WebappClassLoaderBase webappClassLoaderBase =(org.apache.catalina.loader.WebappClassLoaderBase) Thread.currentThread().getContextClassLoader();
174                 StandardContext standardContext = (StandardContext)webappClassLoaderBase.getResources().getContext();
175                 persistenceManager=standardContext.getManager();
176             }
a6a76f 177             return persistenceManager ;
484907 178         }catch (Exception e){
F 179             e.printStackTrace();
180             return null;
181         }
a6a76f 182     }
F 183     
184     
185     /**
186      * 返回 tomcat 真实的 session (从 tomcat 内存中取session数 ) 
187      * @param request
188      * @return
189      */
190     public static HttpSession getSession(HttpServletRequest request,String sessionId) {
191         try
192         {
193             HttpSession localSession = sessions.get(sessionId) ;
194             if (localSession != null) {
195                 return localSession ;
196             }
197             
198             Manager persistenceManager = getPersistenceManager( request) ;
199             if (persistenceManager == null) {
200                 return null ;
201             }
202             Session session = persistenceManager.findSession(sessionId);
203             return (session != null ? session.getSession():null) ;
204         } catch(SecurityException e) {
205             e.printStackTrace();
206         }catch(IllegalArgumentException e) {
207             e.printStackTrace();
208         }catch (IOException e) {    
209             e.printStackTrace();
210         }
211         return null ;
212     }
213     
214     /**
215      * 返回在线用户
216      * @param dbId
217      * @return
218      */
219     public static List<OnlineUserEntity> getOnLineUser(HttpServletRequest request,String dbId) {
220         List<OnlineUserEntity> onlineUserList = null ;
221         try {
222             Session[] sessions = getSessions( request) ;
223             //for (Entry<String,HttpSession> entry:sessions.entrySet()) {    
224             //        HttpSession session = entry.getValue(); 
225             for (int i = 0 ;sessions != null && i < sessions.length;i++) {
226                 HttpSession session = sessions[i].getSession();
227                 
228                 if (session != null) {
229                     String sessDbid = getDatabaseId(session) ;   //获取会话 session 里面的 dbid 
230                     if (sessDbid == null || "".equals(dbId)) {
231                         continue ;
232                     }
233                     
234                     if (sessDbid != null && dbId != null && sessDbid.equals(dbId)) {
235                         String sessionId = session.getId();
236                         
237                         String userCode = null ;
238                         if (session.getAttribute(SessionKey.USERCODE) != null) {
239                             userCode = (String)session.getAttribute(SessionKey.USERCODE) ;
240                         }
241                         if (userCode == null && session.getAttribute(SessionKey.HRCODE)!=null ) {
242                             userCode = (String)session.getAttribute(SessionKey.HRCODE) ;
243                         }
244                         
245                         if (userCode == null || "".equals(userCode)) {
246                             continue ;
247                         }
248                         
249                         String userName = (session.getAttribute(SessionKey.USER_NAME) == null?"":(String) session.getAttribute(SessionKey.USER_NAME)) ;
250                         Date loginDate = (session.getCreationTime() == 0 ? null :new Date(session.getCreationTime()) ) ;
251                         
252                         OnlineUserEntity onlineUserEntity = new OnlineUserEntity() ;
253                         onlineUserEntity.setLoginType(Integer.parseInt(session.getAttribute(SessionKey.USER_LOGIN_TYPE)==null?"1":session.getAttribute(SessionKey.USER_LOGIN_TYPE)+""));
254                         onlineUserEntity.setSessionId(sessionId).setUserCode(userCode).setUserName(userName).setLoginDate(loginDate);
255                         if (onlineUserList == null) {
256                             onlineUserList = new ArrayList<OnlineUserEntity>() ;
257                         }
258                         onlineUserList.add(onlineUserEntity);
259                     }
260                 }
261             }
262         }catch (Exception e) {
263             e.printStackTrace();
264             throw e ;
265         }
266         return onlineUserList ;
267     }
e98f5c 268     /**
F 269      * 删除所有在线用户
270      * @param dbid
271      * @return
272      */
273     public static void delAllOnLineUser(String dbid) {
274         try {
275             Session[] sessions = getSessions( null) ;
484907 276             RedisTemplate redisTemplate = (RedisTemplate) FactoryBean.getBean("redisTemplate");
e98f5c 277             for(Session session:sessions){
F 278                 HttpSession localSession=  session.getSession();
279                 String sessDbid = getDatabaseId(localSession ) ;   //获取会话 session 里面的 dbid
280                 if (sessDbid == null || !sessDbid.equals(dbid)) {
281                     continue ;
282                 }
256eb8 283                 if(localSession!=null) {
F 284                     if (localSession.getAttribute(SessionKey.USER_LOGIN_TYPE).equals(SessionKey.USER_LOGIN_TYPE_APP)) {
484907 285                         //因为token只在app才有,所以才加上面的判断
256eb8 286                         redisTemplate.delete(InvitationCode.TOKEN_STR + localSession.getAttribute(SessionKey.DATA_BASE_ID) + ":" + localSession.getAttribute(SessionKey.USERCODE));
F 287                     }
484907 288                     localSession.setAttribute("isClose",true);
256eb8 289                     localSession.invalidate(); //删除该会话
484907 290                 }
F 291             }
292         }catch (Exception e) {
293             e.printStackTrace();
294         }
295     }
296     /**
297      * 删除所有登录端(pc,app)的用户信息
298      * @param dbid
299      * @return
300      */
301     public static void delAllOnLineUser(String dbid,String userCode) {
302         try {
303             Session[] sessions = getSessions( null) ;
304             RedisTemplate redisTemplate = (RedisTemplate) FactoryBean.getBean("redisTemplate");
305             for(Session session:sessions){
306                 HttpSession localSession=  session.getSession();
307                 String sessDbid = getDatabaseId(localSession ) ;   //获取会话 session 里面的 dbid
308                 if (sessDbid == null || !sessDbid.equals(dbid)) {
309                     continue ;
310                 }
311                 if(localSession!=null) {
312                     if(userCode.equalsIgnoreCase(localSession.getAttribute(SessionKey.USERCODE)+"")) {
313                         //指定用户
314                         if (localSession.getAttribute(SessionKey.USER_LOGIN_TYPE).equals(SessionKey.USER_LOGIN_TYPE_APP)) {
315                             //因为token只在app才有,所以才加上面的判断
316                             redisTemplate.delete(InvitationCode.TOKEN_STR + localSession.getAttribute(SessionKey.DATA_BASE_ID) + ":" + localSession.getAttribute(SessionKey.USERCODE));
317                         }
318                         localSession.setAttribute("isClose", true);
319                         localSession.invalidate(); //删除该会话
320                     }
e98f5c 321                 }
F 322             }
323         }catch (Exception e) {
324             e.printStackTrace();
325         }
326     }
a6a76f 327     /**
F 328      * 删除在线用户
329      * @param dbId
330      * @return
331      */
332     public static boolean delOnLineUser(HttpServletRequest request,String sessionId) {
333         boolean found = false ; 
334         try {
335             HttpSession localSession = sessions.get(sessionId) ;
336             if (localSession!= null) {
337                     //如果是APP的会话则需要把token也消除 by danaus 2020/3/16 14:55
338                     if (localSession.getAttribute(SessionKey.USER_LOGIN_TYPE).equals(SessionKey.USER_LOGIN_TYPE_APP)) {
339                         RedisTemplate redisTemplate = (RedisTemplate) FactoryBean.getBean("redisTemplate");
340                         redisTemplate.delete(InvitationCode.TOKEN_STR + localSession.getAttribute(SessionKey.DATA_BASE_ID) + ":" + localSession.getAttribute(SessionKey.USERCODE));
341                     }
342                 localSession.invalidate(); //删除该会话
343                 //removeAllSessionKey(localSession) ;
344                 return true ;
345             }
346             
347             Manager persistenceManager = getPersistenceManager( request) ;
348             if (persistenceManager == null) {
349                 return false ;
350             }
351             Session session = persistenceManager.findSession(sessionId);
352             if (session != null) {
353                 session.getSession().invalidate();
354                 //removeAllSessionKey(localSession) ;
355                 return true ;
356             }
357             
358         }catch (Exception e) {
359             e.printStackTrace();
360         }
361         return found ;
362     }
363
364     /**
365      * 返回所有在线用数量
366      * @return
367      */
368     public static int getOnLineUserCount(HttpServletRequest request) {
369         int count = 0 ;
370         try {
371             //for (Entry<String,HttpSession> entry:sessions.entrySet()) {        
372             //    HttpSession session = entry.getValue(); 
373             Session[] sessions = getSessions(request) ;
374             for (int i = 0 ;sessions != null && i < sessions.length;i ++) {
375                 HttpSession session = sessions[i].getSession();    
376                 
377                 String dbId = getDatabaseId(session) ;
378                 if(dbId!=null&&!"".equals(dbId)){
379                     
380                     String userCode = null ;
381                     if (session.getAttribute(SessionKey.USERCODE) != null) {
382                         userCode = (String)session.getAttribute(SessionKey.USERCODE) ;
383                     }
384                     if (userCode == null && session.getAttribute(SessionKey.HRCODE)!=null ) {
385                         userCode = (String)session.getAttribute(SessionKey.HRCODE) ;
386                     }
387                     
388                     if (userCode == null || "".equals(userCode)) {
389                         continue ;
390                     }
391                     count ++ ;
392                 }
393             }
394         }catch (Exception e) {
395             e.printStackTrace();
396             throw e ;
397         }
398         return count ;
399     }    
400     
401     /**
402      * 加载全部或条件查询系统在线人数
403      * @param lookup
404      * @return
405      */
406     public static String getLookup(HttpServletRequest request,String lookup) {
407         List<Map<String, String>> listm = new ArrayList<Map<String, String>>();
408         List<String> li = new ArrayList<String>();
409         Map<String, Object> companyM = new HashMap<String, Object>();
410         long day = 0;
411         long hour = 0;
412         long min = 0;
413         //int count = 0;
414         try {
415             lookup = (lookup.equals("系统名称、域名") ? "" : lookup);
416             SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm");// 设置日期格式
417             long time1 = df.parse(df.format(new Date())).getTime(); // 系统当前时间
418             try {
419                 SpObserver.setDBtoDemo();
420                 OtherMailIfc oterIfc = (OtherMailIfc) FactoryBean.getBean("OtherMailImpl");
421                 List<Map<String, Object>> companylist = oterIfc.getCompanyName();
422                 for (Map<String, Object> compan : companylist) {
423                     companyM.put(compan.get("id").toString(), compan.get("systemID"));
424                 }
425             } catch (Exception e) {
426                 e.printStackTrace();
427             } finally {
428                 SpObserver.setDBtoInstance();
429             }
430             
431             
432             //for (Entry<String,HttpSession> entry:sessions.entrySet()) {        
433             //    HttpSession session = entry.getValue(); 
434             Session[] sessions = getSessions(request) ;
435             for (int i = 0 ;sessions != null && i < sessions.length;i ++) {
436                 HttpSession session = sessions[i].getSession();
437                 String dbId = getDatabaseId(session) ;
438                 
439                 
440                 if (dbId != null && !"".equals(dbId)) {
441                     try {
442                         String userCode = null ;
443                         if (session.getAttribute(SessionKey.USERCODE) != null) {
444                             userCode = (String)session.getAttribute(SessionKey.USERCODE) ;
445                         }
446                         if (userCode == null && session.getAttribute(SessionKey.HRCODE)!=null ) {
447                             userCode = (String)session.getAttribute(SessionKey.HRCODE) ;
448                         }
449                         
450                         if (userCode == null || "".equals(userCode)) {
451                             continue ;
452                         }
453                         //count ++ ;
454                         Map<String, String> lookm = new HashMap<String, String>();
455                         String domain = session.getAttribute(SessionKey.DOMAIN).toString();
456                         String userName = session.getAttribute(SessionKey.USER_NAME).toString();
457                         String dbid = session.getAttribute(SessionKey.DATA_BASE_ID).toString();
458                         String company = (String) companyM.get(dbid);
459                         if (company.toLowerCase().indexOf(lookup.toLowerCase()) != -1
460                                 || domain.toLowerCase().indexOf(lookup.toLowerCase()) != -1 || lookup.equals("")
461                                 || lookup.equals(null)) {
462                             long time2 = df.parse(df.format(new Date(session.getCreationTime()))).getTime();
463                             long diff = time1 - time2;
464                             day = diff / (24 * 60 * 60 * 1000);
465                             hour = (diff / (60 * 60 * 1000) - day * 24);
466                             min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
467                             String longtime = (hour > 0 ? hour + "时" + min + "分钟" : min + "分钟");
468                             lookm.put(dbid,
469                                     company + ";" + domain + ";" + userName + ";"
470                                             + df.format(new Date(session.getCreationTime())) + ";" + longtime + ";"
471                                             + session.getId());
472                             listm.add(lookm);
473                             li.add(dbid);
474                         }
475                     } catch (Exception e) {
476                         continue;
477                     }            
478                     
479                 }
480             
481             
482             }
483             
484             HashSet<String> hs = new HashSet<String>(li);
485             return  listm.size()+"@"+gethtml(hs, listm);
486         } catch (Exception e) {
487             e.printStackTrace();
488         }finally {
489             listm.clear();
490             li.clear();
491             companyM.clear();
492         }
493         return null;
494     }    
495
496     /**
497      * 返回html里的tr内容
498      * @param looklist 系统在线人数信息
499      * @return
500      */
501     public static String gethtml(HashSet<String> li, List<Map<String, String>> listm) {
502         String inner = "";
503         try {
504             int ac = 1;
505             for (String dbid : li) {
506                 inner += "<dt><a href=\"#accordion" + ac + "\" aria-expanded=\"false\" aria-controls=\"accordion" + ac
507                         + "\" " + "class=\"accordion-title accordionTitle js-accordionTrigger\">[#title]"
508                                 + "<font size=\"1\"> ([#cont])</font></a></dt>"
509                         + "<dd class=\"accordion-content accordionItem is-collapsed\" id=\"accordion" + ac
510                         + "\" aria-hidden=\"true\">"
511                         + "<ul class=\"menu\"><li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;域名</li>"
512                         + "<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;用户</li>"
513                         + "<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;登录时间</li>"
514                         + "<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;在线时长</li>"
515                         + "<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
516                         + "&nbsp;&nbsp;&nbsp;操作</li>" + "</ul><br><hr>";
517                 ac++;
518                 int cont = 0;
519                 for (Map<String, String> keymap : listm) {
520                     if (keymap.get(dbid) == null) {
521                         continue;
522                     }
523                     cont++;
524                     inner += "<ul class=\"menus\">";
525                     String[] columns = keymap.get(dbid).toString().split(";");
526                     inner = inner.replace("[#title]", columns[0]);
527                     for (int j = 1; j < columns.length; j++)
528                         if (j == columns.length - 1) {
529                             inner += "<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
530                                     + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[<a href=\"javascript:delOnlineUser('"
531                                     + columns[5] + "');\">踢除</a>]</li>";
532                         } else {
533                             if (j > 1) {
534                                 inner += "<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + columns[j] + "</li>";
535                             } else {
536                                 inner += "<li>" + columns[j] + "</li>";
537                             }
538
539                         }
540                     inner += "</ul><br><hr>";
541                 }
542                 inner = inner.replace("[#cont]", cont+"个用户在线");
543                 inner += "</br><ul class=\"menus\"><li>小计:" + cont + "个用户在线</li></ul>";
544                 inner += "</dd>";
545             }
546         } catch (Exception e) {
547             return inner;
548         }
549         return inner;
550     }    
551     
552     /**
553      * 10天在线人数统计
554      * @param looktenday 时间段
555      * @return
556      */    
557     @SuppressWarnings("static-access")
558     public static String getTendays(String lookTenDay, int conts) throws SQLException {
559         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
560         String inthtml = "";
561         try {
562             Date start = null;
563             Date end = null;
564             Calendar rightNow = Calendar.getInstance();
565             if (lookTenDay.equals("today")) {
566                 Date nowDate = new Date();
567                 rightNow.setTime(nowDate);
568                 rightNow.add(rightNow.DATE, -9);
569                 start = rightNow.getTime();
570                 end = nowDate;
571             } else {
572                 end = df.parse(lookTenDay);
573                 rightNow.setTime(end);
574                 rightNow.add(rightNow.DATE, -9);
575                 start = rightNow.getTime();
576             }
577             try {
578                 OtherMailIfc oterIfc = (OtherMailIfc) FactoryBean.getBean("OtherMailImpl");
579                 List<Map<String, Object>> idlist = null;
580                 int count = 0;
581                 try {
582                     SpObserver.setDBtoDemo();
583                     idlist = oterIfc.getOnBusDBSourseID(conts);
584                     count = oterIfc.getCountDBSourseID();
585                 } catch (Exception e) {
586                     e.printStackTrace();
587                 } finally {
588                     SpObserver.setDBtoInstance();
589                 }
590                 UserAccountServiceIfc userAccountServiceIfc = (UserAccountServiceIfc) FactoryBean
591                         .getBean("UserAccountServiceImpl");
592                 //String htmltxt = "";
593                 Map<String, Integer> contMap = new HashMap<String, Integer>();// 计算在线人数总和
594                                                                                 // 集合
595                 for (Map<String, Object> m : idlist) {
596                     try {
597                         SpObserver.setDBtoInstance("_" + m.get("id").toString());
598                         List<Map<String, String>> list = userAccountServiceIfc.StatisticUserLoginByDay(start, end);
599                         if (list != null) {// 如果没有则关闭
600                             inthtml += getTenhtml(inthtml, (String) m.get("systemID"), contMap, list); // 返回10天统计html里的tr内容
601                         }
602                     } catch (Exception e2) {
603                         if (!e2.getLocalizedMessage().equals("")) {
604                             System.out.print(e2.getLocalizedMessage() + "[" + m.get("bd") + "]");
605                         }
606                         continue;
607                     } finally {
608                         SpObserver.setDBtoInstance();
609                     }
610                 }
611                 // 返回组装好的tr标签
612                 inthtml = inthtml + getConts(count, contMap);
613             } catch (Exception e) {
614                 return e.getCause().getMessage();
615             }
616         } catch (Exception e1) {
617             return e1.getCause().getMessage();
618         }
619         return inthtml;
620     }
621     
622     
623     /**
624      * 返回10天统计html里的tr内容
625      * @param inthtml 显示栏
626      * @param systemID 每一个系统名称
627      * @param contMap 计算在线人数总数
628      * @param listhtml tr标签内容
629      * @return
630      */
631     public static String getTenhtml(String inthtml,String systemID,Map<String, Integer> contMap,List<Map<String,String>> listhtml){
632         String inner="";
633         String dbtxt="";
634         int conts=0;
635         try {        
636                  inner+="<tr align=\"center\" class=\"adadad\"><td>系统名称</td>";
637                  dbtxt+="<tr align=\"center\" class=\"conts\"><td>"+systemID+"</td>";
638                          for (int i = 0; i < listhtml.size(); i++) {
639                              inner+="<td>"+listhtml.get(i).get("dt")+"</td>";
640                              dbtxt+="<td>"+listhtml.get(i).get("counts")+"</td>";
641                              conts+=Integer.parseInt(listhtml.get(i).get("counts"));
642                              contMap.put(listhtml.get(i).get("id"), 
643                                      (Integer) (contMap.get(listhtml.get(i).get("id"))==null?
644                                      Integer.parseInt(listhtml.get(i).get("counts")):
645                                      (contMap.get(listhtml.get(i).get("id"))+Integer.parseInt(listhtml.get(i).get("counts")))));
646                         }
647                          inner+="<td>合计</td></tr>";
648                          dbtxt+="<td class=\"conts\">"+conts+"</td></tr>";
649                          contMap.put(String.valueOf((listhtml.size()+1)), contMap.get(String.valueOf(listhtml.size()+1))==null?
650                                  conts:(contMap.get(String.valueOf(listhtml.size()+1))+conts));
651             if (inthtml.equals("")) {
652                 dbtxt=inner+dbtxt;
653             }            
654         } catch (Exception e) {
655             return inner;
656         }
657         return dbtxt;
658     }
659     
660     /**
661      * 计算在线人数总和
662      * @param count 页码计算
663      * @param contMap 在线人数总数集合
664      * @return
665      */
666     public static String getConts(int count,Map<String, Integer> contMap){
667         String page="<tr align=\"center\" class=\"conts\"><td>合计</td>";
668         try {            
669             for (int i = 1; i < contMap.size()+1; i++) {
670                 page+="<td >"+contMap.get(String.valueOf(i))+"</td>";
671             }
672             page+="</tr><tr align=\"center\"><td colspan=\"12\">"
673                     + "<a href=\"javascript:pagelook(1);\">第1页</a>&nbsp;&nbsp;";
674             if (count>19) {
675                 double uble=(double)count/19;
676                 int number=(int) Math.ceil(uble);
677                 for (int i = 1; i <number ; i++) {
678                     page+="<a href=\"javascript:pagelook("+19*i+");\">第"+(i+1)+"页</a>&nbsp;&nbsp;";
679                    }        
680             }    
681         } catch (Exception e) {
682             // TODO: handle exception 
683             return page;
684         }finally{
685             contMap=null;
686             count=0;
687         }
688         return page;
689     }
690     
691     
692     @Override
693     public void sessionDestroyed(HttpSessionEvent event) {
694         try {
695             InitLicense.getInstance().pusSessionCount();//给加密狗用,作为单个客户计数使用
696             HttpSession session = event.getSession();
697             String sessionId = session.getId();
698             String dbId = getDatabaseId(session) ;
484907 699             if(dbId!=null&&!"".equals(dbId)&&session.getAttribute("isClose")==null) {
F 700                 //----session.getAttribute("isClose")!=null表示手动退出系统,不需要发送通知
701                 //---增加下面处理是为了重启tomcat服务时不需要发送6017的消息,因为是主动关闭系统 by danaus 2023-06-27 14:56
702                 String reloadStatus = "reload=0";
703                 try {
704                     reloadStatus = FileUtils.readFileToString((new File(servletContextPath + "r.conf")), "UTF-8");
705                 } catch (FileNotFoundException e) {
706                     //没文件则新建
707                     FileUtil.writeFile("reload=0", servletContextPath + "r.conf");
708                 }
709                 if ("reload=0".equalsIgnoreCase(reloadStatus))
710                 {//reload=1表示是脚本重启tomcat服务,不需要发送通知
711                     try {
712                         SpObserver.setDBtoInstance("_" + dbId);
713                         UserAccountServiceIfc userAccountServiceIfc = (UserAccountServiceIfc) FactoryBean.getBean("UserAccountServiceImpl");
714                         userAccountServiceIfc.doQuitLog(sessionId);   //更新 _sysloginlog 日志表
715                         //发送会话失效通知
716                         MessageInfo messageInfo = new MessageInfo();
717                         messageInfo.setDbId(Integer.parseInt(dbId));
718                         messageInfo.setMsgType(MessageType.RELOGIN_PAGE);
719                         messageInfo.setUserFromType(session.getAttribute(SessionKey.USER_LOGIN_TYPE) + "");
720                         messageInfo.setUserCode(session.getAttribute(SessionKey.USERCODE) + "");
721                         messageInfo.setSessionId(sessionId);
722                         messageInfo.setMsg("您已太长时间没有操作,请重新登录");
723                         WebSocketMessageServer.publishMessageToRedis(messageInfo);
724                     } catch (Exception e) {
725                         e.printStackTrace();
726                     } finally {
727                         SpObserver.setDBtoInstance();
728                     }
a6a76f 729                 }
F 730             }
731             sessions.remove(sessionId);
484907 732         }catch(IOException e ) {
F 733             e.printStackTrace();
a6a76f 734         }catch(Exception e ) {
F 735             e.printStackTrace();
736             throw e ;
737         }
738     }
739     
740 //    public static HttpSession getSession(String id){
741 //        return sessions.get(id);
742 //    }
743     
744 //    public static Map<String,HttpSession> getSessions() {
745 //        return sessions ;
746 //    }
747
748     /**
749      * 删除 dbid 所有会话信息
750      * @param dbId
751      * @return
752      */
753     public static int delSession(HttpServletRequest request,String dbId) {
754         int count = 0 ;
755         try {
756             
757             //for (Entry<String,HttpSession> entry:sessions.entrySet()) {        
758             //    HttpSession session = entry.getValue(); 
759             Session[] sessions = getSessions(request) ;
760             for (int i = 0 ;sessions != null && i < sessions.length;i ++) {
761                 HttpSession session = sessions[i].getSession();
762                 //System.out.println(  "正在检查 delSession() sessionid:" + session.getId());
763                 if (session != null) {
764                     String sessDbid = getDatabaseId(session) ;   //获取会话 session 里面的 dbid 
765                     
766                     if (sessDbid != null && dbId != null && sessDbid.equals(dbId)) {
767                         String userCode = null ;
768                         if (session.getAttribute(SessionKey.USERCODE) != null) {
769                             userCode = (String)session.getAttribute(SessionKey.USERCODE) ;
770                         }
771                         if (userCode == null && session.getAttribute(SessionKey.HRCODE)!=null ) {
772                             userCode = (String)session.getAttribute(SessionKey.HRCODE) ;
773                         }
774                         
775                         if (userCode == null || "".equals(userCode)) {
776                             continue ;
777                         }
484907 778                         session.setAttribute("isClose",true);
a6a76f 779                         //先不删除会话信息,因再次使用时,会导致 Session already invalidated 错误,用 removeAllSessionKey 过程代替
F 780                         session.invalidate();   //删除会话 ,
781                         
782                         //removeAllSessionKey(session) ;
783                         count ++ ;
784                     }
785                 }
786             }
787         }catch (Exception e) {
788             e.printStackTrace();
789             throw e ;
790         }
791         return count ;
792     }
793     
794     /**
795      * 删除会话所有键值
796      * @param session
797      */
798     public static void removeAllSessionKey (HttpSession session) {
799         Enumeration<String> enumeration =session.getAttributeNames();//获取session中所有的键值对
800         //遍历enumeration中的键值对
801         while(enumeration.hasMoreElements()){
802             String key=enumeration.nextElement().toString();//获取session中的键值
803             session.removeAttribute(key);
804         }
805     }
806     
807     public static String getDatabaseId(HttpSession session) {
808         String sessDbid = null ;
809         if (session.getAttribute(SessionKey.DATA_BASE_ID) != null) {
810             sessDbid = (String)session.getAttribute(SessionKey.DATA_BASE_ID) ;
811         }
812         if (sessDbid == null || "".equals(sessDbid) ) {
813             sessDbid = (String)session.getAttribute(SessionKey.SHOPPING_DBID);
814         }
815         return sessDbid ;
816     }
817 }