aboutsummaryrefslogtreecommitdiffstats
path: root/tests/src/test/java/org/whispersystems/libaxolotl/InMemorySessionStore.java
blob: 2d03d43779663de4e528cb1cc77cc5f04d731351 (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
package org.whispersystems.libaxolotl;

import org.whispersystems.libaxolotl.state.SessionRecord;
import org.whispersystems.libaxolotl.state.SessionStore;
import org.whispersystems.libaxolotl.util.Pair;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class InMemorySessionStore implements SessionStore {

  private Map<Pair<Long, Integer>, byte[]> sessions = new HashMap<>();

  public InMemorySessionStore() {}

  @Override
  public synchronized SessionRecord loadSession(long recipientId, int deviceId) {
    try {
      if (containsSession(recipientId, deviceId)) {
        return new SessionRecord(sessions.get(new Pair<>(recipientId, deviceId)));
      } else {
        return new SessionRecord();
      }
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }

  @Override
  public synchronized List<Integer> getSubDeviceSessions(long recipientId) {
    List<Integer> deviceIds = new LinkedList<>();

    for (Pair<Long, Integer> key : sessions.keySet()) {
      if (key.first() == recipientId) {
        deviceIds.add(key.second());
      }
    }

    return deviceIds;
  }

  @Override
  public synchronized void storeSession(long recipientId, int deviceId, SessionRecord record) {
    sessions.put(new Pair<>(recipientId, deviceId), record.serialize());
  }

  @Override
  public synchronized boolean containsSession(long recipientId, int deviceId) {
    return sessions.containsKey(new Pair<>(recipientId, deviceId));
  }

  @Override
  public synchronized void deleteSession(long recipientId, int deviceId) {
    sessions.remove(new Pair<>(recipientId, deviceId));
  }

  @Override
  public synchronized void deleteAllSessions(long recipientId) {
    for (Pair<Long, Integer> key : sessions.keySet()) {
      if (key.first() == recipientId) {
        sessions.remove(key);
      }
    }
  }
}