diff --git a/extensions/wikidata/src/org/openrefine/wikidata/utils/EntityCache.java b/extensions/wikidata/src/org/openrefine/wikidata/utils/EntityCache.java index b27a4abf1..360183470 100644 --- a/extensions/wikidata/src/org/openrefine/wikidata/utils/EntityCache.java +++ b/extensions/wikidata/src/org/openrefine/wikidata/utils/EntityCache.java @@ -7,6 +7,7 @@ import org.wikidata.wdtk.datamodel.interfaces.EntityDocument; import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue; import org.wikidata.wdtk.wikibaseapi.ApiConnection; import org.wikidata.wdtk.wikibaseapi.WikibaseDataFetcher; +import org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; @@ -15,27 +16,42 @@ import com.google.common.cache.LoadingCache; public class EntityCache { private static EntityCache _entityCache = new EntityCache(); - private LoadingCache _cache; + private LoadingCache _cache = null; private WikibaseDataFetcher _fetcher; - private EntityCache() { ApiConnection connection = ApiConnection.getWikidataApiConnection(); _fetcher = new WikibaseDataFetcher(connection, Datamodel.SITE_WIKIDATA); + System.out.println("Creating fresh cache"); _cache = CacheBuilder.newBuilder() .maximumSize(4096) .expireAfterWrite(1, TimeUnit.HOURS) .build( - new CacheLoader() { - public EntityDocument load(EntityIdValue entityId) throws Exception { - EntityDocument doc = _fetcher.getEntityDocument(entityId.getId()); - return doc; + new CacheLoader() { + public EntityDocument load(String entityId) throws Exception { + EntityDocument doc = _fetcher.getEntityDocument(entityId); + if (doc != null) { + return doc; + } else { + throw new MediaWikiApiErrorException("400", "Unknown entity id \""+entityId+"\""); + } } }); } - public static EntityDocument getEntityDocument(EntityIdValue qid) { - return _entityCache._cache.apply(qid); + public EntityDocument get(EntityIdValue id) { + return _cache.apply(id.getId()); + } + + public static EntityCache getEntityCache() { + if (_entityCache == null) { + _entityCache = new EntityCache(); + } + return _entityCache; + } + + public static EntityDocument getEntityDocument(EntityIdValue id) { + return getEntityCache().get(id); } }