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 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(); } }