blob: 58bb5f6941fe9ef4e74ac01937a8dadd47b368d0 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
/*
* Copyright 2013 Jesse Morgan
*/
package com.p4square.grow.frontend.session;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
import org.restlet.Response;
import org.restlet.Request;
import org.restlet.data.CookieSetting;
import org.restlet.security.User;
/**
* Singleton Session Manager.
*
* @author Jesse Morgan <jesse@jesterpm.net>
*/
public class Sessions {
private static final String COOKIE_NAME = "S";
private static final Sessions THE = new Sessions();
public static Sessions getInstance() {
return THE;
}
private final Map<String, Session> mSessions;
private Sessions() {
mSessions = new ConcurrentHashMap<String, Session>();
}
public Session get(String sessionid) {
Session s = mSessions.get(sessionid);
if (s != null && !s.isExpired()) {
s.touch();
return s;
}
return null;
}
/**
* Get the Session associated with the Request.
* @return A session or null if no session is found.
*/
public Session get(Request request) {
final String cookie = request.getCookies().getFirstValue(COOKIE_NAME);
if (cookie != null) {
return get(cookie);
}
return null;
}
public Session create(User user) {
if (user == null) {
throw new IllegalArgumentException("Can not create session for null user.");
}
Session s = new Session(user);
mSessions.put(s.getId(), s);
return s;
}
/**
* Create a new Session and add the Session cookie to the response.
*/
public Session create(Request request, Response response) {
Session s = create(request.getClientInfo().getUser());
CookieSetting cookie = new CookieSetting(COOKIE_NAME, s.getId());
cookie.setPath("/");
request.getCookies().add(cookie);
response.getCookieSettings().add(cookie);
return s;
}
}
|