1 package dst.ass1.kv.impl;
3 import dst.ass1.kv.ISessionManager;
4 import dst.ass1.kv.SessionCreationFailedException;
5 import dst.ass1.kv.SessionNotFoundException;
6 import redis.clients.jedis.Jedis;
7 import redis.clients.jedis.Transaction;
11 public class SessionManager implements ISessionManager {
12 // "sUser:${userId}" -> UUID - Reverse-sessiondata-userId-mapping.
13 private final static String SUSER = "sUser:";
14 // "sData:${UUID}" -> hashmap - Sessiondata.
15 private final static String SDATA = "sData:";
17 private final Jedis jedis; // no lightsabers :(
19 public SessionManager(String host, int port) {
20 jedis = new Jedis(host, port);
24 public String createSession(Long userId, int timeToLive) throws SessionCreationFailedException {
25 jedis.del(SUSER + userId.toString());
26 return requireSession(userId, timeToLive);
30 public void setSessionVariable(String sessionId, String key, String value) throws SessionNotFoundException {
31 if (!jedis.exists(SDATA + sessionId)) throw new SessionNotFoundException("Unknown sessionId:" + sessionId);
32 jedis.hset(SDATA + sessionId, key, value);
36 public String getSessionVariable(String sessionId, String key) throws SessionNotFoundException {
37 if (!jedis.exists(SDATA + sessionId)) throw new SessionNotFoundException("Unknown sessionId:" + sessionId);
38 return jedis.hget(SDATA + sessionId, key);
42 public Long getUserId(String sessionId) throws SessionNotFoundException {
43 if (!jedis.exists(SDATA + sessionId)) throw new SessionNotFoundException("Unknown sessionId:" + sessionId);
44 return Long.valueOf(jedis.hget(SDATA + sessionId, "userId"));
48 public int getTimeToLive(String sessionId) throws SessionNotFoundException {
49 if (!jedis.exists(SDATA + sessionId)) throw new SessionNotFoundException("Unknown sessionId:" + sessionId);
50 return jedis.ttl(SDATA + sessionId).intValue();
54 public String requireSession(Long userId, int timeToLive) throws SessionCreationFailedException {
55 String uuid = jedis.get(SUSER + userId.toString());
57 uuid = UUID.randomUUID().toString();
58 jedis.watch(SUSER + userId.toString());
59 Transaction t = jedis.multi();
60 t.set(SUSER + userId.toString(), uuid);
61 t.expire(SUSER + userId.toString(), timeToLive);
62 t.hset(SDATA + uuid, "userId", userId.toString());
63 t.expire(SDATA + uuid, timeToLive);