1
2
3
4
5
6
7
8
9
10
11
12
13
14 package org.eclipse.jetty.security;
15
16 import java.security.SecureRandom;
17 import java.util.HashMap;
18 import java.util.Map;
19 import java.util.Random;
20
21 import javax.servlet.http.Cookie;
22 import javax.servlet.http.HttpServletRequest;
23 import javax.servlet.http.HttpServletResponse;
24
25
26
27
28 public class HashCrossContextPsuedoSession<T> implements CrossContextPsuedoSession<T>
29 {
30 private final String _cookieName;
31
32 private final String _cookiePath;
33
34 private final Random _random = new SecureRandom();
35
36 private final Map<String, T> _data = new HashMap<String, T>();
37
38 public HashCrossContextPsuedoSession(String cookieName, String cookiePath)
39 {
40 this._cookieName = cookieName;
41 this._cookiePath = cookiePath == null ? "/" : cookiePath;
42 }
43
44 public T fetch(HttpServletRequest request)
45 {
46 for (Cookie cookie : request.getCookies())
47 {
48 if (_cookieName.equals(cookie.getName()))
49 {
50 String key = cookie.getValue();
51 return _data.get(key);
52 }
53 }
54 return null;
55 }
56
57 public void store(T datum, HttpServletResponse response)
58 {
59 String key;
60
61 synchronized (_data)
62 {
63
64 while (true)
65 {
66 key = Long.toString(Math.abs(_random.nextLong()), 30 + (int) (System.currentTimeMillis() % 7));
67 if (!_data.containsKey(key)) break;
68 }
69
70 _data.put(key, datum);
71 }
72
73 Cookie cookie = new Cookie(_cookieName, key);
74 cookie.setPath(_cookiePath);
75 response.addCookie(cookie);
76 }
77
78 public void clear(HttpServletRequest request)
79 {
80 for (Cookie cookie : request.getCookies())
81 {
82 if (_cookieName.equals(cookie.getName()))
83 {
84 String key = cookie.getValue();
85 _data.remove(key);
86 break;
87 }
88 }
89 }
90 }