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 public class HashCrossContextPsuedoSession<T> implements CrossContextPsuedoSession<T>
34 {
35 private final String _cookieName;
36
37 private final String _cookiePath;
38
39 private final Random _random = new SecureRandom();
40
41 private final Map<String, T> _data = new HashMap<String, T>();
42
43 public HashCrossContextPsuedoSession(String cookieName, String cookiePath)
44 {
45 this._cookieName = cookieName;
46 this._cookiePath = cookiePath == null ? "/" : cookiePath;
47 }
48
49 public T fetch(HttpServletRequest request)
50 {
51 Cookie[] cookies = request.getCookies();
52 if (cookies == null)
53 return null;
54
55 for (Cookie cookie : cookies)
56 {
57 if (_cookieName.equals(cookie.getName()))
58 {
59 String key = cookie.getValue();
60 return _data.get(key);
61 }
62 }
63 return null;
64 }
65
66 public void store(T datum, HttpServletResponse response)
67 {
68 String key;
69
70 synchronized (_data)
71 {
72
73 while (true)
74 {
75 key = Long.toString(Math.abs(_random.nextLong()), 30 + (int) (System.currentTimeMillis() % 7));
76 if (!_data.containsKey(key)) break;
77 }
78
79 _data.put(key, datum);
80 }
81
82 Cookie cookie = new Cookie(_cookieName, key);
83 cookie.setPath(_cookiePath);
84 response.addCookie(cookie);
85 }
86
87 public void clear(HttpServletRequest request)
88 {
89 for (Cookie cookie : request.getCookies())
90 {
91 if (_cookieName.equals(cookie.getName()))
92 {
93 String key = cookie.getValue();
94 _data.remove(key);
95 break;
96 }
97 }
98 }
99 }