View Javadoc

1   /***
2    * 
3    */
4   package hu.elte.tribus.services;
5   
6   import hu.elte.tribus.interfaces.OnlineUserBean;
7   import hu.elte.tribus.interfaces.UserDao;
8   import hu.elte.tribus.interfaces.UserTracker;
9   import hu.elte.tribus.model.Conversation;
10  import hu.elte.tribus.model.User;
11  
12  import java.sql.SQLException;
13  import java.util.ArrayList;
14  import java.util.Date;
15  import java.util.HashMap;
16  import java.util.Iterator;
17  import java.util.List;
18  import java.util.Map;
19  
20  import org.apache.log4j.Logger;
21  import org.hibernate.HibernateException;
22  import org.hibernate.Session;
23  import org.springframework.orm.hibernate3.HibernateCallback;
24  import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
25  
26  /***
27   * Very simple implementation, that fits the need of a single-server environment
28   * using a HashMap or even a clustered environment with a jcache implementation 
29   * with a simple factory bean.
30   * Which is of course beyound scope for a 48-hours welding contest.
31   * 
32   * @author kocka
33   */
34  public class HashMapUserTracker extends HibernateDaoSupport implements UserTracker {
35  	
36  	private final static Logger logger = Logger.getLogger(HashMapUserTracker.class);
37  
38  	private UserDao userDao;
39  	
40  	/***
41  	 * Map of users (username -> login time)
42  	 */
43  	private Map<String, Date> map = new HashMap<String, Date>();
44  
45  	public void userLoggedIn(String username) {
46  		map.put(username, new Date());
47  		if(logger.isInfoEnabled()) {
48  			logger.info("User logged in:"+username);
49  		}
50  	}
51  
52  	public void userLoggedOut(String username) {
53  		map.remove(username);
54  	}
55  
56  	public Map getMap() {
57  		return map;
58  	}
59  
60  	public void setMap(Map map) {
61  		this.map = map;
62  	}
63  
64  	public List listOfOnlineUsers() {
65  		return (List)getHibernateTemplate().execute(new HibernateCallback(){
66  
67  			public Object doInHibernate(Session session) throws HibernateException, SQLException {
68  				ArrayList list = new ArrayList();
69  				Iterator iterator = map.keySet().iterator();
70  				while(iterator.hasNext()) {
71  					String userName = (String)iterator.next();
72  					User user = userDao.getUser(userName);
73  					Conversation conversation = (Conversation) session.createQuery(" from "+Conversation.class.getName()+" where enddate is null").uniqueResult();
74  					OnlineUserBean onlineUserBean = new OnlineUserBean();
75  					onlineUserBean.setUser(user);
76  					onlineUserBean.setOnlineSince((Date) map.get(userName));
77  					onlineUserBean.setConversation(conversation);
78  					list.add(onlineUserBean);
79  				}
80  				return list;
81  			}});
82  	}
83  
84  	public UserDao getUserDao() {
85  		return userDao;
86  	}
87  
88  	public void setUserDao(UserDao userDao) {
89  		this.userDao = userDao;
90  	}
91  
92  }