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