RoutesCache.java (1844B)
1 package xyz.kebigon.housesearch.file; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.Collection; 6 import java.util.HashMap; 7 import java.util.Map; 8 9 import com.fasterxml.jackson.core.JsonGenerationException; 10 import com.fasterxml.jackson.core.JsonParseException; 11 import com.fasterxml.jackson.databind.JsonMappingException; 12 import com.fasterxml.jackson.databind.ObjectMapper; 13 14 import lombok.AccessLevel; 15 import lombok.Data; 16 import lombok.NoArgsConstructor; 17 import lombok.extern.slf4j.Slf4j; 18 import xyz.kebigon.housesearch.domain.Route; 19 20 @Slf4j 21 @Data 22 @NoArgsConstructor(access = AccessLevel.PRIVATE) 23 public class RoutesCache 24 { 25 private static final File ROUTES_CACHE_FILE = new File("var/state/routes-cache.json"); 26 static 27 { 28 ROUTES_CACHE_FILE.getParentFile().mkdirs(); 29 } 30 31 private Map<String, Collection<Route>> cache = new HashMap<>(); 32 33 public Collection<Route> get(String cacheKey) 34 { 35 return cache.get(cacheKey); 36 } 37 38 public void put(String cacheKey, Collection<Route> routes) 39 { 40 cache.put(cacheKey, routes); 41 } 42 43 public void save() throws JsonGenerationException, JsonMappingException, IOException 44 { 45 log.info("Saving {} routes to {}", cache.size(), ROUTES_CACHE_FILE.getAbsolutePath()); 46 final ObjectMapper mapper = new ObjectMapper(); 47 mapper.writeValue(ROUTES_CACHE_FILE, this); 48 } 49 50 public static RoutesCache load() throws JsonParseException, JsonMappingException, IOException 51 { 52 if (ROUTES_CACHE_FILE.exists()) 53 { 54 log.info("Loading routes cache from {}", ROUTES_CACHE_FILE.getAbsolutePath()); 55 56 final ObjectMapper mapper = new ObjectMapper(); 57 return mapper.readValue(ROUTES_CACHE_FILE, RoutesCache.class); 58 } 59 else 60 return new RoutesCache(); 61 } 62 }