1 16 17 package org.javabb.infra; 18 19 import java.util.Date ; 20 import java.util.HashSet ; 21 import java.util.Map ; 22 import java.util.Set ; 23 24 import org.apache.commons.logging.Log; 25 import org.apache.commons.logging.LogFactory; 26 import org.javabb.vo.Topic; 27 import org.javabb.vo.User; 28 29 import com.opensymphony.webwork.ServletActionContext; 30 import com.opensymphony.xwork.ActionContext; 31 32 37 public class UserContext { 38 39 private static final Log LOG = LogFactory.getLog(UserContext.class); 40 41 private static final Date DEFAULT_LAST_VISIT_TIMESTAMP = new Date (0); 42 45 public static final String KEY_USER_CONTEXT = "javabb.user.context"; 46 47 private User _user = null; 48 private Date _lastVisitTimestamp = null; 49 private Set _readTopicIds = new HashSet (); 50 51 54 public synchronized static UserContext getContext() { 55 Map session = ActionContext.getContext().getSession(); 56 if(session == null){ 57 return null; 58 } 59 60 if (!session.containsKey(KEY_USER_CONTEXT)) { 61 session.put(KEY_USER_CONTEXT, new UserContext()); 62 } 63 return (UserContext) session.get(KEY_USER_CONTEXT); 64 } 65 66 69 public User getUser() { 70 return _user; 71 } 72 73 77 public void setUser(User user) { 78 if (_user == null && user != null) { 79 _lastVisitTimestamp = user.getLastVisitTimestamp(); 80 } 81 _user = user; 82 ActionContext.getContext().getSession().put("jbbuser", _user); 83 ServletActionContext.getRequest().getSession().putValue("jbbuser", _user); 84 } 85 86 89 public boolean isAuthenticated() { 90 return _user != null; 91 } 92 93 public void deauthenticate() { 94 _user = null; 95 ActionContext.getContext().getSession().remove("jbbuser"); 96 } 97 98 101 public Date getLastVisitTimestamp() { 102 if (_lastVisitTimestamp == null) { 103 return DEFAULT_LAST_VISIT_TIMESTAMP; 104 } 105 return _lastVisitTimestamp; 106 } 107 108 public boolean isTopicRead(Topic topic) { 109 try { 110 boolean beforeLastVisit = topic.getLastPostDate().before(getLastVisitTimestamp()); 111 return _readTopicIds.contains(topic.getId()) || beforeLastVisit; 112 } catch (RuntimeException e) { 113 return true; 114 } 115 } 116 117 public void setTopicRead(Long topicId) { 118 _readTopicIds.add(topicId); 119 } 120 121 public void setTopicUnread(Long topicId) { 122 _readTopicIds.remove(topicId); 123 } 124 } 125 | Popular Tags |