com.frightanic.smn.core.GeoAdmin Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of open-data-smn Show documentation
Show all versions of open-data-smn Show documentation
An API to serve publicly available data from the SwissMetNet.
package com.frightanic.smn.core;
import com.frightanic.smn.OpenDataSmnConfiguration;
import com.frightanic.smn.api.SmnData;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class GeoAdmin {
private static final String SMN_DATA_CACHE_KEY = "smn";
private final Logger logger = LoggerFactory.getLogger(GeoAdmin.class);
private final DataLoader dataLoader;
private final LoadingCache cache;
private SmnData lastLoadedSmnData;
public GeoAdmin(OpenDataSmnConfiguration configuration) {
dataLoader = new DataLoader(configuration.getDataUrl());
cache = CacheBuilder.newBuilder().
expireAfterWrite(configuration.getDataCacheTimeToLiveMinutes(), TimeUnit.MINUTES).
build(new SmnDataCacheLoader());
}
public SmnData getSmnData() throws IOException {
try {
return cache.get(SMN_DATA_CACHE_KEY);
} catch (ExecutionException | RuntimeException e) {
if (lastLoadedSmnData == null) {
throw new IOException(e);
} else {
logger.warn(
"Loading data via the cache's data loader failed (cache was empty). Returning last available data" + " set.");
return lastLoadedSmnData;
}
}
}
private class SmnDataCacheLoader extends CacheLoader {
public SmnData load(String key) throws IOException {
SmnData smnData = dataLoader.loadSmnData();
if (smnData != null) {
logger.info("Loaded SMN data from geo.admin portal. Keeping an internal copy");
lastLoadedSmnData = smnData;
}
return smnData;
}
}
}