blob: 3ec00123597c022e10624502f82b17a02849f68d (
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
|
package design.persistence;
import com.fasterxml.jackson.databind.ObjectMapper;
import design.model.Golfer;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class JSONPersonalDatabase implements PersonalDatabase {
private final Map<String, Golfer> cache;
private final ObjectMapper mapper;
private final File file;
public JSONPersonalDatabase(String filename) throws IOException {
this.file = new File(filename);
this.cache = new HashMap<>();
this.mapper = new ObjectMapper();
load();
}
private void load() throws IOException {
Golfer[] data = mapper.readValue(file, Golfer[].class);
cache.clear();
for (Golfer i : data) {
cache.put(i.getUsername(), i);
}
}
private void save() throws IOException {
Golfer[] data = cache.values().toArray(Golfer[]::new);
mapper.writeValue(file, data);
}
@Override
public Golfer[] getGolfers() {
return new Golfer[0];
}
@Override
public Golfer getGolfer(String username) {
return cache.get(username);
}
@Override
public void addGolfer(Golfer golfer) throws IOException {
cache.put(golfer.getUsername(), golfer);
save();
}
@Override
public void removeGolfer(Golfer golfer) throws IOException {
cache.remove(golfer.getUsername());
save();
}
@Override
public void updateGolfer(Golfer golfer) throws IOException {
cache.put(golfer.getUsername(), golfer);
save();
}
}
|