package design.persistence; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import design.model.Course; import design.model.Hole; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class CSVMasterDatabase implements MasterDatabase { private final List cache; private final CsvMapper mapper; private final File file; public CSVMasterDatabase(String filename) throws IOException { this.cache = new ArrayList<>(); this.mapper = new CsvMapper(); this.file = new File(filename); SimpleModule module = new SimpleModule(); module.addDeserializer(Course.class, new CourseDeserializer()); mapper.registerModule(module); load(); } public void load() throws IOException { MappingIterator it = mapper .readerFor(Course.class) .with(CsvSchema.emptySchema().withHeader()) .readValues(file); cache.addAll(it.readAll()); } @Override public Course[] getCourses() { return cache.toArray(Course[]::new); } @Override public Course getCourse(String name) { return null; } private static class CourseDeserializer extends JsonDeserializer { @Override public Course deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { ObjectNode node = p.getCodec().readTree(p); String name = node.get("Course Name").asText(); double difficulty = node.get("Difficulty Rating").asDouble(); String location = node.get("Location").asText(); int holes = node.get("Number of Holes").asInt(); int totalPar = node.get("Total Par").asInt(); String[] parValues = node.get("Par Per Hole").asText().split(";"); List holeList = new ArrayList<>(); for (int i = 0; i < parValues.length; i++) { holeList.add(new Hole(i + 1, Integer.parseInt(parValues[i].trim()))); } return new Course(name, (int) difficulty, location, holes, totalPar, holeList); } } }