blob: 1fc1e92f96322cacb3c1e9886f8da9944618abea (
plain) (
blame)
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
|
package com.ufund.api.ufundapi.persistence;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ufund.api.ufundapi.model.UserAuth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Component
public class UserAuthFIleDAO implements UserAuthDAO {
private final Map<String, UserAuth> userAuthMap;
private final ObjectMapper objectMapper;
private final String filename;
public UserAuthFIleDAO(ObjectMapper objectMapper, @Value("${authKeys.file}") String filename) throws IOException {
this.userAuthMap = new HashMap<>();
this.objectMapper = objectMapper;
this.filename = filename;
load();
}
/**
* Loads the data from the file into the map
*
* @throws IOException Thrown if there was an issue reading the file
*/
private void load() throws IOException {
userAuthMap.clear();
UserAuth[] userAuthKeysArray = objectMapper.readValue(new File(filename), UserAuth[].class);
for (UserAuth userAuth : userAuthKeysArray) {
userAuthMap.put(userAuth.getKey(), userAuth);
}
}
/**
* Saves the data from the map into the json file
*
* @throws IOException Thrown on any problem writing the file
*/
private void save() throws IOException {
objectMapper.writeValue(new File(filename), userAuthMap.values());
}
@Override
public UserAuth getUserAuth(String key) {
synchronized (userAuthMap) {
return userAuthMap.get(key);
}
}
@Override
public void addUserAuth(UserAuth userAuth) throws IOException {
synchronized (userAuthMap) {
userAuthMap.put(userAuth.getKey(), userAuth);
save();
}
}
@Override
public void removeUserAuth(String key) throws IOException {
synchronized (userAuthMap) {
userAuthMap.remove(key);
save();
}
}
}
|