Search in sources :

Example 26 with CacheKey

use of com.facebook.cache.common.CacheKey in project fresco by facebook.

the class ImagePipelineTest method testEvictFromDiskCache.

@Test
public void testEvictFromDiskCache() {
    String uriString = "http://dummy/string";
    Uri uri = Uri.parse(uriString);
    CacheKey dummyCacheKey = mock(CacheKey.class);
    List<CacheKey> list = new ArrayList<>();
    list.add(dummyCacheKey);
    MultiCacheKey multiKey = new MultiCacheKey(list);
    when(mCacheKeyFactory.getEncodedCacheKey(any(ImageRequest.class), anyObject())).thenReturn(multiKey);
    mImagePipeline.evictFromDiskCache(uri);
    verify(mMainDiskStorageCache).remove(multiKey);
    verify(mSmallImageDiskStorageCache).remove(multiKey);
}
Also used : MultiCacheKey(com.facebook.cache.common.MultiCacheKey) ImageRequest(com.facebook.imagepipeline.request.ImageRequest) ArrayList(java.util.ArrayList) Uri(android.net.Uri) CacheKey(com.facebook.cache.common.CacheKey) MultiCacheKey(com.facebook.cache.common.MultiCacheKey) BitmapMemoryCacheKey(com.facebook.imagepipeline.cache.BitmapMemoryCacheKey) SimpleCacheKey(com.facebook.cache.common.SimpleCacheKey) Test(org.junit.Test)

Example 27 with CacheKey

use of com.facebook.cache.common.CacheKey in project fresco by facebook.

the class EncodedMemoryCacheProducer method produceResults.

@Override
public void produceResults(final Consumer<EncodedImage> consumer, final ProducerContext producerContext) {
    final String requestId = producerContext.getId();
    final ProducerListener listener = producerContext.getListener();
    listener.onProducerStart(requestId, PRODUCER_NAME);
    final ImageRequest imageRequest = producerContext.getImageRequest();
    final CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest, producerContext.getCallerContext());
    CloseableReference<PooledByteBuffer> cachedReference = mMemoryCache.get(cacheKey);
    try {
        if (cachedReference != null) {
            EncodedImage cachedEncodedImage = new EncodedImage(cachedReference);
            cachedEncodedImage.setEncodedCacheKey(cacheKey);
            try {
                listener.onProducerFinishWithSuccess(requestId, PRODUCER_NAME, listener.requiresExtraMap(requestId) ? ImmutableMap.of(EXTRA_CACHED_VALUE_FOUND, "true") : null);
                consumer.onProgressUpdate(1f);
                consumer.onNewResult(cachedEncodedImage, true);
                return;
            } finally {
                EncodedImage.closeSafely(cachedEncodedImage);
            }
        }
        if (producerContext.getLowestPermittedRequestLevel().getValue() >= ImageRequest.RequestLevel.ENCODED_MEMORY_CACHE.getValue()) {
            listener.onProducerFinishWithSuccess(requestId, PRODUCER_NAME, listener.requiresExtraMap(requestId) ? ImmutableMap.of(EXTRA_CACHED_VALUE_FOUND, "false") : null);
            consumer.onNewResult(null, true);
            return;
        }
        Consumer consumerOfInputProducer = new EncodedMemoryCacheConsumer(consumer, mMemoryCache, cacheKey);
        listener.onProducerFinishWithSuccess(requestId, PRODUCER_NAME, listener.requiresExtraMap(requestId) ? ImmutableMap.of(EXTRA_CACHED_VALUE_FOUND, "false") : null);
        mInputProducer.produceResults(consumerOfInputProducer, producerContext);
    } finally {
        CloseableReference.closeSafely(cachedReference);
    }
}
Also used : ImageRequest(com.facebook.imagepipeline.request.ImageRequest) PooledByteBuffer(com.facebook.common.memory.PooledByteBuffer) EncodedImage(com.facebook.imagepipeline.image.EncodedImage) CacheKey(com.facebook.cache.common.CacheKey)

Example 28 with CacheKey

use of com.facebook.cache.common.CacheKey in project fresco by facebook.

the class SplitCachesByImageSizeDiskCachePolicyTest method setUp.

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    List<CacheKey> keys = new ArrayList<>(1);
    keys.add(new SimpleCacheKey("http://dummy.uri"));
    mCacheKey = new MultiCacheKey(keys);
    when(mCacheKeyFactory.getEncodedCacheKey(mImageRequest, mCallerContext)).thenReturn(mCacheKey);
    when(mImageRequest.getCacheChoice()).thenReturn(ImageRequest.CacheChoice.DEFAULT);
    when(mImageRequest.isDiskCacheEnabled()).thenReturn(true);
    mIsCancelled = new AtomicBoolean(false);
    mEncodedImage = new EncodedImage(CloseableReference.of(mImagePooledByteBuffer));
    mSplitCachesByImageSizeDiskCachePolicy = new SplitCachesByImageSizeDiskCachePolicy(mDefaultBufferedDiskCache, mSmallImageBufferedDiskCache, mCacheKeyFactory, FORCE_SMALL_CACHE_THRESHOLD);
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MultiCacheKey(com.facebook.cache.common.MultiCacheKey) ArrayList(java.util.ArrayList) SimpleCacheKey(com.facebook.cache.common.SimpleCacheKey) EncodedImage(com.facebook.imagepipeline.image.EncodedImage) CacheKey(com.facebook.cache.common.CacheKey) MultiCacheKey(com.facebook.cache.common.MultiCacheKey) SimpleCacheKey(com.facebook.cache.common.SimpleCacheKey) Before(org.junit.Before)

Example 29 with CacheKey

use of com.facebook.cache.common.CacheKey in project fresco by facebook.

the class DiskStorageCacheTest method testCacheFile.

/**
   * Tests size based file eviction of cache files. Also tests that unexpected
   * files (which are not in the format expected by the cache) do not count
   * towards the cache size, and are also evicted during both evictions (LRU and Old).
   *
   * @throws Exception
   */
@Test
public void testCacheFile() throws Exception {
    if (!mCacheDirectory.exists() && !mCacheDirectory.mkdirs()) {
        throw new RuntimeException("Cannot create cache dir");
    }
    // Write non-cache, non-lru file in the cache directory
    File unexpected1 = new File(mCacheDirectory, "unexpected1");
    RandomAccessFile rf1 = new RandomAccessFile(unexpected1, "rw");
    rf1.setLength(110);
    // Touch the non-cache, non-lru file, and assert that it succeeds.
    when(mClock.now()).thenReturn(TimeUnit.HOURS.toMillis(1));
    assertTrue(unexpected1.setLastModified(mClock.now()));
    // 1. Add first cache file
    CacheKey key1 = new SimpleCacheKey("foo");
    byte[] value1 = new byte[101];
    // just so it's not all zeros for the equality test below.
    value1[80] = 'c';
    mCache.insert(key1, WriterCallbacks.from(value1));
    // verify resource
    assertArrayEquals(value1, getContents(getResource(key1)));
    // 1. Touch the LRU file, and assert that it succeeds.
    when(mClock.now()).thenReturn(TimeUnit.HOURS.toMillis(2));
    assertTrue(mCache.probe(key1));
    // The cache size should be the size of the first file only
    // The unexpected files should not count towards size
    assertTrue(mCache.getSize() == 101);
    // Write another non-cache, non-lru file in the cache directory
    File unexpected2 = new File(mCacheDirectory, "unexpected2");
    RandomAccessFile rf2 = new RandomAccessFile(unexpected2, "rw");
    rf2.setLength(120);
    // Touch the non-cache, non-lru file, and assert that it succeeds.
    when(mClock.now()).thenReturn(TimeUnit.HOURS.toMillis(3));
    assertTrue(unexpected2.setLastModified(mClock.now()));
    // 2. Add second cache file
    CacheKey key2 = new SimpleCacheKey("bar");
    byte[] value2 = new byte[102];
    // just so it's not all zeros for the equality test below.
    value2[80] = 'd';
    mCache.insert(key2, WriterCallbacks.from(value2));
    // 2. Touch the LRU file, and assert that it succeeds.
    when(mClock.now()).thenReturn(TimeUnit.HOURS.toMillis(4));
    assertTrue(mCache.probe(key2));
    // The cache size should be the size of the first + second cache files
    // The unexpected files should not count towards size
    assertTrue(mCache.getSize() == 203);
    // At this point, the filecache size has exceeded
    // FILE_CACHE_MAX_SIZE_HIGH_LIMIT. However, eviction will be triggered
    // only when the next value will be inserted (to be more particular,
    // before the next value is inserted).
    // 3. Add third cache file
    CacheKey key3 = new SimpleCacheKey("foobar");
    byte[] value3 = new byte[103];
    // just so it's not all zeros for the equality test below.
    value3[80] = 'e';
    mCache.insert(key3, WriterCallbacks.from(value3));
    // At this point, the first file should have been evicted. Only the
    // files associated with the second and third entries should be in cache.
    // 1. Verify that the first cache, lru files are deleted
    assertNull(getResource(key1));
    // Verify the first unexpected file is deleted, but that eviction stops
    // before the second unexpected file
    assertFalse(unexpected1.exists());
    assertFalse(unexpected2.exists());
    // 2. Verify the second cache, lru files exist
    assertArrayEquals(value2, getContents(getResource(key2)));
    // 3. Verify that cache, lru files for third entry still exists
    assertArrayEquals(value3, getContents(getResource(key3)));
    // The cache size should be the size of the second + third files
    assertTrue(String.format(Locale.US, "Expected cache size of %d but is %d", 205, mCache.getSize()), mCache.getSize() == 205);
    // Write another non-cache, non-lru file in the cache directory
    File unexpected3 = new File(mCacheDirectory, "unexpected3");
    RandomAccessFile rf3 = new RandomAccessFile(unexpected3, "rw");
    rf3.setLength(120);
    assertTrue(unexpected3.exists());
    // After a clear, cache file size should be uninitialized (-1)
    mCache.clearAll();
    assertEquals(-1, mCache.getSize());
    assertFalse(unexpected3.exists());
    assertNull(getResource(key2));
    assertNull(getResource(key3));
}
Also used : RandomAccessFile(java.io.RandomAccessFile) SimpleCacheKey(com.facebook.cache.common.SimpleCacheKey) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) CacheKey(com.facebook.cache.common.CacheKey) MultiCacheKey(com.facebook.cache.common.MultiCacheKey) SimpleCacheKey(com.facebook.cache.common.SimpleCacheKey) PrepareOnlyThisForTest(org.powermock.core.classloader.annotations.PrepareOnlyThisForTest) Test(org.junit.Test)

Example 30 with CacheKey

use of com.facebook.cache.common.CacheKey in project fresco by facebook.

the class DiskStorageCacheTest method testTimeEvictionClearsIndex.

@Test
public void testTimeEvictionClearsIndex() throws Exception {
    when(mClock.now()).thenReturn(5l);
    CacheKey key = putOneThingInCache();
    mCache.clearOldEntries(4);
    assertFalse(mCache.hasKeySync(key));
    assertFalse(mCache.hasKey(key));
}
Also used : CacheKey(com.facebook.cache.common.CacheKey) MultiCacheKey(com.facebook.cache.common.MultiCacheKey) SimpleCacheKey(com.facebook.cache.common.SimpleCacheKey) PrepareOnlyThisForTest(org.powermock.core.classloader.annotations.PrepareOnlyThisForTest) Test(org.junit.Test)

Aggregations

CacheKey (com.facebook.cache.common.CacheKey)49 SimpleCacheKey (com.facebook.cache.common.SimpleCacheKey)31 MultiCacheKey (com.facebook.cache.common.MultiCacheKey)29 Test (org.junit.Test)22 PrepareOnlyThisForTest (org.powermock.core.classloader.annotations.PrepareOnlyThisForTest)19 ImageRequest (com.facebook.imagepipeline.request.ImageRequest)10 EncodedImage (com.facebook.imagepipeline.image.EncodedImage)8 ArrayList (java.util.ArrayList)8 CloseableImage (com.facebook.imagepipeline.image.CloseableImage)7 BinaryResource (com.facebook.binaryresource.BinaryResource)5 BitmapMemoryCacheKey (com.facebook.imagepipeline.cache.BitmapMemoryCacheKey)5 File (java.io.File)5 PooledByteBuffer (com.facebook.common.memory.PooledByteBuffer)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4 Before (org.junit.Before)4 Uri (android.net.Uri)3 FileBinaryResource (com.facebook.binaryresource.FileBinaryResource)3 WriterCallback (com.facebook.cache.common.WriterCallback)3 CloseableReference (com.facebook.common.references.CloseableReference)3 IOException (java.io.IOException)3