package com.ufund.api.ufundapi.persistence; import com.fasterxml.jackson.databind.ObjectMapper; import com.ufund.api.ufundapi.model.UserAuth; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; @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(); } private void load() throws IOException { userAuthMap.clear(); UserAuth[] userAuthKeysArray = objectMapper.readValue(new File(filename), UserAuth[].class); for (UserAuth userAuth : userAuthKeysArray) { userAuthMap.put(userAuth.getKey(), userAuth); } } private void save() throws IOException { objectMapper.writeValue(new File(filename), userAuthMap.values()); } public UserAuth[] getAuthKeys() { synchronized (userAuthMap) { return userAuthMap.values().toArray(UserAuth[]::new); } } @Override public UserAuth getUserAuth(String key) { synchronized (userAuthMap) { return userAuthMap.get(key); } } @Override public boolean addUserAuth(UserAuth userAuth) throws IOException { synchronized (userAuthMap) { userAuthMap.put(userAuth.getKey(), userAuth); save(); return true; } } }