1 package dolda.jsvc.util;
5 import java.security.SecureRandom;
7 public class Session implements java.io.Serializable {
8 private static final Map<String, Session> sessions = new HashMap<String, Session>();
9 private static final SecureRandom prng;
10 private static long lastclean = 0;
11 private final Map<Object, Object> props = new HashMap<Object, Object>();
12 private long ctime = System.currentTimeMillis(), atime = ctime, etime = 86400 * 1000;
13 private Collection<Listener> ll = new HashSet<Listener>();
17 prng = SecureRandom.getInstance("SHA1PRNG");
18 } catch(java.security.NoSuchAlgorithmException e) {
23 public static interface Listener {
24 public void expire(Session sess);
27 public void listen(Listener l) {
33 public Object get(Object key, Object def) {
35 if(props.containsKey(key))
36 return(props.get(key));
42 public Object put(Object key, Object val) {
44 return(props.put(key, val));
48 private void expire() {
55 public static int num() {
56 synchronized(sessions) {
57 return(sessions.size());
61 private static String newid() {
62 byte[] rawid = new byte[16];
63 prng.nextBytes(rawid);
64 StringBuilder buf = new StringBuilder();
66 buf.append(Misc.int2hex((b & 0xf0) >> 4, false));
67 buf.append(Misc.int2hex(b & 0x0f, false));
69 return(buf.toString());
72 private static Session create(Request req) {
73 Session sess = new Session();
76 ct = Integer.parseInt(req.ctx().libconfig("jsvc.session.expire", "0"));
79 ct = Integer.parseInt(req.ctx().sysconfig("jsvc.session.expire", "0"));
85 private static void clean() {
86 long now = System.currentTimeMillis();
87 synchronized(sessions) {
88 for(Iterator<Session> i = sessions.values().iterator(); i.hasNext();) {
89 Session sess = i.next();
90 if(now > sess.atime + sess.etime) {
98 public static Session get(Request req) {
99 long now = System.currentTimeMillis();
100 if(now - lastclean > 3600 * 1000) {
105 MultiMap<String, Cookie> cookies = Cookie.get(req);
106 Cookie sc = cookies.get("jsvc-session");
108 synchronized(sessions) {
110 sess = sessions.get(sc.value);
114 sessions.put(id, sess);
115 sc = new Cookie("jsvc-session", id);
116 sc.expires = new Date(System.currentTimeMillis() + (86400L * 365L * 1000L));
117 sc.path = req.ctx().sysconfig("jsvc.session.path", req.rooturl().getPath());
118 String pd = req.ctx().sysconfig("jsvc.session.domain", null);
127 public static Session get() {
128 return(get(RequestThread.request()));