public CacheItem put(final String url, final Object obj, DateTime expiresAt) { if (obj == null) { return null; } Timber.d(String.format("put(%s)", url)); CacheItem d = new CacheItem(obj, expiresAt); if (null != mMemoryCache) { mMemoryCache.put(url, d); } if (null != mDiskCache) { checkNotOnMainThread(); final String key = transformUrlForDiskCacheKey(url); final ReentrantLock lock = getLockForDiskCacheEdit(key); lock.lock(); try { DiskLruCache.Editor editor = mDiskCache.edit(key); writeValueToDisk(editor.newOutputStream(0), obj); writeExpirationToDisk(editor.newOutputStream(1), expiresAt); editor.commit(); } catch (IOException e) { e.printStackTrace(); } finally { lock.unlock(); scheduleDiskCacheFlush(); } } return d; }
public boolean containsInDiskCache(String url) { if (null != mDiskCache) { checkNotOnMainThread(); try { return null != mDiskCache.get(transformUrlForDiskCacheKey(url)); } catch (IOException e) { e.printStackTrace(); } } return false; }
public void remove(String url) { if (null != mMemoryCache) { mMemoryCache.remove(url); } if (null != mDiskCache) { checkNotOnMainThread(); try { mDiskCache.remove(transformUrlForDiskCacheKey(url)); scheduleDiskCacheFlush(); } catch (IOException e) { e.printStackTrace(); } } }
public CacheItem getFromDiskCache(final String url, boolean checkExpiration) { CacheItem result = null; if (null != mDiskCache) { checkNotOnMainThread(); try { final String key = transformUrlForDiskCacheKey(url); DiskLruCache.Snapshot snapshot = mDiskCache.get(key); if (null != snapshot) { Object value = readValueFromDisk(snapshot.getInputStream(0)); DateTime expiresAt = new DateTime(readExpirationFromDisk(snapshot.getInputStream(1))); if (value != null) { if (checkExpiration && expiresAt.isBeforeNow()) { mDiskCache.remove(key); scheduleDiskCacheFlush(); } else { result = new CacheItem(value, expiresAt); if (null != mMemoryCache) { mMemoryCache.put(url, result); } } } else { // If we get here, the file in the cache can't be // decoded. Remove it and schedule a flush. mDiskCache.remove(key); scheduleDiskCacheFlush(); } } } catch (IOException e) { Timber.e(e, "getFromDiskCache failed."); } } return result; }