package com.ufund.api.ufundapi.persistence; import java.io.File; import java.io.IOException; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.ufund.api.ufundapi.model.UserAuth; @Component public class UserAuthFIleDAO implements UserAuthDAO { private final Map userAuthMap; private final ObjectMapper objectMapper; private final String filename; public UserAuthFIleDAO(ObjectMapper objectMapper, @Value("${authKeys.file}") String filename) throws IOException { this.userAuthMap = new HashMap<>(); this.objectMapper = objectMapper; this.filename = filename; load(); } /** * Loads the data from the file into the map * * @throws IOException Thrown if there was an issue reading the file */ private void load() throws IOException { userAuthMap.clear(); UserAuth[] userAuthKeysArray = objectMapper.readValue(new File(filename), UserAuth[].class); for (UserAuth userAuth : userAuthKeysArray) { if (userAuth.getExpiration().isAfter(LocalDateTime.now())) { userAuthMap.put(userAuth.getKey(), userAuth); } } } /** * Saves the data from the map into the json file * * @throws IOException Thrown on any problem writing the file */ private void save() throws IOException { objectMapper.writeValue(new File(filename), userAuthMap.values()); } @Override public UserAuth getUserAuth(String key) { synchronized (userAuthMap) { return userAuthMap.get(key); } } @Override public void addUserAuth(UserAuth userAuth) throws IOException { synchronized (userAuthMap) { userAuthMap.put(userAuth.getKey(), userAuth); save(); } } @Override public void removeUserAuth(String key) throws IOException { synchronized (userAuthMap) { userAuthMap.remove(key); save(); } } }