package com.ufund.api.ufundapi.persistence; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.TreeMap; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.ufund.api.ufundapi.model.Need; @Component public class CupboardFileDAO implements CupboardDAO { private final Map needs; // cache private final ObjectMapper objectMapper; private int nextId; private final String filename; public CupboardFileDAO(@Value("${cupboard.file}") String filename, ObjectMapper objectMapper) throws IOException { this.filename = filename; this.objectMapper = objectMapper; needs = new TreeMap<>(); load(); } private synchronized int nextId() { int id = nextId; nextId++; return id; } /** * Load changes from the json file * * @throws IOException Any IO issue with the file */ private void load() throws IOException { needs.clear(); nextId = 0; Need[] needsArray = objectMapper.readValue(new File(filename), Need[].class); for (Need need : needsArray) { needs.put(need.getId(), need); if (need.getId() > nextId()) { nextId = need.getId(); } } nextId++; } /** * Saves the needs to json * * @throws IOException If there was an IO issue saving the file */ private void save() throws IOException { Need[] needArray = needs.values().toArray(Need[]::new); objectMapper.writeValue(new File(filename), needArray); } @Override public Need[] getNeeds() { synchronized (needs) { return needs.values().toArray(Need[]::new); } } @Override public Need getNeed(int id) { synchronized (needs) { return needs.getOrDefault(id, null); } } @Override public Need addNeed(Need need) throws IOException { synchronized (needs) { Need newNeed = new Need(need); newNeed.setID(nextId()); needs.put(newNeed.getId(), newNeed); save(); return newNeed; } } @Override public Need updateNeed(Need need) throws IOException { synchronized (needs) { if (needs.containsKey(need.getId())) { needs.put(need.getId(), need); save(); return need; } else { return null; } } } @Override public boolean deleteNeed(int id) throws IOException { synchronized (needs) { if (needs.containsKey(id)) { needs.remove(id); save(); return true; } else { return false; } } } }