package design.persistence; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.module.SimpleModule; import design.model.Course; import design.model.Golfer; import design.model.League; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class JSONPersonalDatabase implements PersonalDatabase { private static JSONPersonalDatabase INSTANCE; public static JSONPersonalDatabase instance() { if (INSTANCE == null) { INSTANCE = new JSONPersonalDatabase("data/personaldb.json"); } return INSTANCE; } // static instance strictly for testing, to not add data to personaldb.json static JSONPersonalDatabase testInstance(String filename) { INSTANCE = new JSONPersonalDatabase(filename); return INSTANCE; } private final Map cache; private final ObjectMapper mapper; private final File file; private JSONPersonalDatabase(String filename) { this.file = new File(filename); this.cache = new HashMap<>(); this.mapper = new ObjectMapper(); Serializers.configureMapper(mapper); mapper.registerModule(this.getJacksonModule()); try { load(); } catch (IOException ex) { throw new RuntimeException(ex); } } 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.writer(new Serializers.CustomPrettyPrinter()).writeValue(file, data); } // turns that collection into a real array of golfers @Override public Golfer[] getGolfers() { return cache.values().toArray(Golfer[]::new); } @Override public Golfer getGolfer(String username) { return cache.get(username); } @Override public void addGolfer(Golfer golfer) throws IOException { cache.putIfAbsent(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(); } @Override public void importData(Object rawData) throws IOException { if (!(rawData instanceof Golfer[] data)) { throw new ClassCastException(); } cache.clear(); for (Golfer golfer : data) { cache.put(golfer.getUsername(), golfer); } save(); } @Override public Golfer[] exportData() { return getGolfers(); } @Override public SimpleModule getJacksonModule() { return new SimpleModule() .addSerializer(Course.class, new Serializers.CourseIdSerializer()) .addDeserializer(Course.class, new Serializers.CourseIdDeserializer()) .addSerializer(League.class, new Serializers.LeagueIDSerializer()) .addDeserializer(League.class, new Serializers.LeagueIDDeserializer()); } @Override public Class getTargetClass() { return Golfer[].class; } }