2 // ========================================================================
3 // Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
19 package org.eclipse.jetty.security;
21 import java.security.SecureRandom;
22 import java.util.HashMap;
24 import java.util.Random;
26 import javax.servlet.http.Cookie;
27 import javax.servlet.http.HttpServletRequest;
28 import javax.servlet.http.HttpServletResponse;
31 * @version $Rev: 4660 $ $Date: 2009-02-25 17:29:53 +0100 (Wed, 25 Feb 2009) $
33 public class HashCrossContextPsuedoSession<T> implements CrossContextPsuedoSession<T>
35 private final String _cookieName;
37 private final String _cookiePath;
39 private final Random _random = new SecureRandom();
41 private final Map<String, T> _data = new HashMap<String, T>();
43 public HashCrossContextPsuedoSession(String cookieName, String cookiePath)
45 this._cookieName = cookieName;
46 this._cookiePath = cookiePath == null ? "/" : cookiePath;
49 public T fetch(HttpServletRequest request)
51 Cookie[] cookies = request.getCookies();
55 for (Cookie cookie : cookies)
57 if (_cookieName.equals(cookie.getName()))
59 String key = cookie.getValue();
60 return _data.get(key);
66 public void store(T datum, HttpServletResponse response)
75 key = Long.toString(Math.abs(_random.nextLong()), 30 + (int) (System.currentTimeMillis() % 7));
76 if (!_data.containsKey(key)) break;
79 _data.put(key, datum);
82 Cookie cookie = new Cookie(_cookieName, key);
83 cookie.setPath(_cookiePath);
84 response.addCookie(cookie);
87 public void clear(HttpServletRequest request)
89 for (Cookie cookie : request.getCookies())
91 if (_cookieName.equals(cookie.getName()))
93 String key = cookie.getValue();