com.facebook.cache.common.CacheKey Java Examples

The following examples show how to use com.facebook.cache.common.CacheKey. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DiskStorageCache.java    From fresco with MIT License 6 votes vote down vote up
/**
 * Probes whether the object corresponding to the mKey is in the cache. Note that the act of
 * probing touches the item (if present in cache), thus changing its LRU timestamp.
 *
 * <p>This will be faster than retrieving the object, but it still has file system accesses and
 * should NOT be called on the UI thread.
 *
 * @param key the mKey to check
 * @return whether the keyed mValue is in the cache
 */
public boolean probe(final CacheKey key) {
  String resourceId = null;
  try {
    synchronized (mLock) {
      List<String> resourceIds = CacheKeyUtil.getResourceIds(key);
      for (int i = 0; i < resourceIds.size(); i++) {
        resourceId = resourceIds.get(i);
        if (mStorage.touch(resourceId, key)) {
          mResourceIndex.add(resourceId);
          return true;
        }
      }
      return false;
    }
  } catch (IOException e) {
    SettableCacheEvent cacheEvent =
        SettableCacheEvent.obtain().setCacheKey(key).setResourceId(resourceId).setException(e);
    mCacheEventListener.onReadException(cacheEvent);
    cacheEvent.recycle();
    return false;
  }
}
 
Example #2
Source File: DiskStorageCacheTest.java    From fresco with MIT License 6 votes vote down vote up
@Test
public void testCleanOldCacheNoEntriesRemaining() throws IOException {
  long cacheExpirationMs = TimeUnit.DAYS.toMillis(5);
  CacheKey key1 = new SimpleCacheKey("aaa");
  byte[] value1 = new byte[41];
  mCache.insert(key1, WriterCallbacks.from(value1));

  CacheKey key2 = new SimpleCacheKey("bbb");
  byte[] value2 = new byte[42];
  mCache.insert(key2, WriterCallbacks.from(value2));

  // Increment clock by default expiration time + 1 day
  when(mClock.now()).thenReturn(cacheExpirationMs + TimeUnit.DAYS.toMillis(1));

  long oldestEntry = mCache.clearOldEntries(cacheExpirationMs);
  assertEquals(0L, oldestEntry);
}
 
Example #3
Source File: BufferedDiskCache.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Writes to disk cache
 * @throws IOException
 */
private void writeToDiskCache(
    final CacheKey key,
    final PooledByteBuffer buffer) {
  FLog.v(TAG, "About to write to disk-cache for key %s", key.toString());
  try {
    mFileCache.insert(
        key, new WriterCallback() {
          @Override
          public void write(OutputStream os) throws IOException {
            mPooledByteStreams.copy(buffer.getStream(), os);
          }
        }
    );
    FLog.v(TAG, "Successful disk-cache write for key %s", key.toString());
  } catch (IOException ioe) {
    // Log failure
    // TODO: 3697790
    FLog.w(TAG, ioe, "Failed to write to disk-cache for key %s", key.toString());
  }
}
 
Example #4
Source File: ImagePreviewFragment.java    From redgram-for-reddit with GNU General Public License v3.0 6 votes vote down vote up
private void displayCachedImageFromBackgroundThread(ImageRequest request){
    CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(ImageRequest.fromUri(request.getSourceUri()));

    if(cacheKey != null){
        BinaryResource resource = ImagePipelineFactory.getInstance().getMainDiskStorageCache().getResource(cacheKey);
        if(resource != null){
            File localFile = ((FileBinaryResource) resource).getFile();
            if(localFile != null){
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        imagePreview.setImage(ImageSource.uri(localFile.getPath()));
                    }
                });
            }
        }

    }
}
 
Example #5
Source File: StagingArea.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param key
 * @return value associated with given key or null if no value is associated
 */
public synchronized CloseableReference<PooledByteBuffer> get(final CacheKey key) {
  Preconditions.checkNotNull(key);
  CloseableReference<PooledByteBuffer> storedRef = mMap.get(key);
  if (storedRef != null) {
    synchronized (storedRef) {
      if (!CloseableReference.isValid(storedRef)) {
        // Reference is not valid, this means that someone cleared reference while it was still in
        // use. Log error
        // TODO: 3697790
        mMap.remove(key);
        FLog.w(
            TAG,
            "Found closed reference %d for key %s (%d)",
            System.identityHashCode(storedRef),
            key.toString(),
            System.identityHashCode(key));
        return null;
      }
      storedRef = storedRef.clone();
    }
  }
  return storedRef;
}
 
Example #6
Source File: ImagePreviewPresenter.java    From TLint with Apache License 2.0 6 votes vote down vote up
private InputStream getImageBytesFromLocal(Uri loadUri) {
    if (loadUri == null) {
        return null;
    }
    CacheKey cacheKey = DefaultCacheKeyFactory.getInstance()
            .getEncodedCacheKey(ImageRequest.fromUri(loadUri), null);
    try {
        if (ImagePipelineFactory.getInstance().getMainFileCache().hasKey(cacheKey)) {
            return ImagePipelineFactory.getInstance()
                    .getMainFileCache()
                    .getResource(cacheKey)
                    .openStream();
        }
        if (ImagePipelineFactory.getInstance().getSmallImageFileCache().hasKey(cacheKey)) {
            return ImagePipelineFactory.getInstance()
                    .getSmallImageFileCache()
                    .getResource(cacheKey)
                    .openStream();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #7
Source File: StagingArea.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Removes key-value from the StagingArea. Both key and value must match.
 * @param key
 * @param bufferRef value corresponding to key
 * @return true if item was removed
 */
public synchronized boolean remove(
    final CacheKey key,
    final CloseableReference<PooledByteBuffer> bufferRef) {
  Preconditions.checkNotNull(key);
  Preconditions.checkNotNull(bufferRef);
  Preconditions.checkArgument(CloseableReference.isValid(bufferRef));

  final CloseableReference<?> oldValue = mMap.get(key);

  if (oldValue == null || oldValue.get() != bufferRef.get()) {
    return false;
  }

  mMap.remove(key);
  oldValue.close();
  logStats();
  return true;
}
 
Example #8
Source File: DiskStorageCache.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Retrieves the file corresponding to the mKey, if it is in the cache. Also
 * touches the item, thus changing its LRU timestamp. If the file is not
 * present in the file cache, returns null.
 * <p>
 * This should NOT be called on the UI thread.
 *
 * @param key the mKey to check
 * @return The resource if present in cache, otherwise null
 */
@Override
public BinaryResource getResource(final CacheKey key) {
  try {
    synchronized (mLock) {
      BinaryResource resource = mStorageSupplier.get().getResource(getResourceId(key), key);
      if (resource == null) {
        mCacheEventListener.onMiss();
      } else {
        mCacheEventListener.onHit();
      }
      return resource;
    }
  } catch (IOException ioe) {
    mCacheErrorLogger.logError(
        CacheErrorLogger.CacheErrorCategory.GENERIC_IO,
        TAG,
        "getResource",
        ioe);
    mCacheEventListener.onReadException();
    return null;
  }
}
 
Example #9
Source File: BufferedDiskCache.java    From fresco with MIT License 6 votes vote down vote up
/**
 * Performs key-value loop up in staging area and file cache. Any error manifests itself as a
 * miss, i.e. returns false.
 *
 * @param key
 * @return true if the image is found in staging area or File cache, false if not found
 */
private boolean checkInStagingAreaAndFileCache(final CacheKey key) {
  EncodedImage result = mStagingArea.get(key);
  if (result != null) {
    result.close();
    FLog.v(TAG, "Found image for %s in staging area", key.getUriString());
    mImageCacheStatsTracker.onStagingAreaHit(key);
    return true;
  } else {
    FLog.v(TAG, "Did not find image for %s in staging area", key.getUriString());
    mImageCacheStatsTracker.onStagingAreaMiss(key);
    try {
      return mFileCache.hasKey(key);
    } catch (Exception exception) {
      return false;
    }
  }
}
 
Example #10
Source File: EllipticalGradientPostProcessor.java    From react-native-image-filter-kit with MIT License 6 votes vote down vote up
@Nonnull
@Override
public CacheKey generateCacheKey() {
  return new SimpleCacheKey(String.format(
    Locale.ROOT,
    "elliptical_gradient_%d_%d_%s_%f_%f_%f_%f_%s_%s",
    mWidth,
    mHeight,
    mMixStep.toString(),
    mCenterX,
    mCenterY,
    mRadiusX,
    mRadiusY,
    Arrays.toString(mColors),
    Arrays.toString(mStops)
  ));
}
 
Example #11
Source File: PostProcessorRegistry.java    From react-native-image-filter-kit with MIT License 6 votes vote down vote up
@Nullable
Postprocessor createComposition(
  @Nullable String name,
  int width,
  int height,
  @Nullable JSONObject config,
  @Nonnull CloseableReference<CloseableImage> imageRef,
  @Nonnull CacheKey imageKey,
  @Nonnull Context context
) {
  @Nullable CreateComposition filter = mCompositions.get(name);

  Assertions.assertCondition(
    filter != null,
    "ImageFilterKit: Can't find '" + name + "' filter in registry."
  );

  return filter != null
    ? filter.create(width, height, config, imageRef, imageKey, context)
    : null;
}
 
Example #12
Source File: DiskStorageCacheTest.java    From fresco with MIT License 6 votes vote down vote up
@Test
public void testWithMultiCacheKeys() throws Exception {
  CacheKey insertKey1 = new SimpleCacheKey("foo");
  byte[] value1 = new byte[101];
  value1[50] = 'a'; // just so it's not all zeros for the equality test below.
  mCache.insert(insertKey1, WriterCallbacks.from(value1));

  List<CacheKey> keys1 = new ArrayList<>(2);
  keys1.add(new SimpleCacheKey("bar"));
  keys1.add(new SimpleCacheKey("foo"));
  MultiCacheKey matchingMultiKey = new MultiCacheKey(keys1);
  assertArrayEquals(value1, getContents(mCache.getResource(matchingMultiKey)));

  List<CacheKey> keys2 = new ArrayList<>(2);
  keys2.add(new SimpleCacheKey("one"));
  keys2.add(new SimpleCacheKey("two"));
  MultiCacheKey insertKey2 = new MultiCacheKey(keys2);
  byte[] value2 = new byte[101];
  value1[50] = 'b'; // just so it's not all zeros for the equality test below.
  mCache.insert(insertKey2, WriterCallbacks.from(value2));

  CacheKey matchingSimpleKey = new SimpleCacheKey("one");
  assertArrayEquals(value2, getContents(mCache.getResource(matchingSimpleKey)));
}
 
Example #13
Source File: BufferedDiskCache.java    From fresco with MIT License 6 votes vote down vote up
private Task<Boolean> containsAsync(final CacheKey key) {
  try {
    final Object token = FrescoInstrumenter.onBeforeSubmitWork("BufferedDiskCache_containsAsync");
    return Task.call(
        new Callable<Boolean>() {
          @Override
          public Boolean call() throws Exception {
            final Object currentToken = FrescoInstrumenter.onBeginWork(token, null);
            try {
              return checkInStagingAreaAndFileCache(key);
            } catch (Throwable th) {
              FrescoInstrumenter.markFailure(token, th);
              throw th;
            } finally {
              FrescoInstrumenter.onEndWork(currentToken);
            }
          }
        },
        mReadExecutor);
  } catch (Exception exception) {
    // Log failure
    // TODO: 3697790
    FLog.w(TAG, exception, "Failed to schedule disk-cache read for %s", key.getUriString());
    return Task.forError(exception);
  }
}
 
Example #14
Source File: DiskStorageCacheTest.java    From fresco with MIT License 5 votes vote down vote up
@Test
public void testCacheEventListener() throws Exception {
  // 1. Add first cache file
  CacheKey key1 = new SimpleCacheKey("foo");
  int value1Size = 101;
  byte[] value1 = new byte[value1Size];
  value1[80] = 'c'; // just so it's not all zeros for the equality test below.
  BinaryResource resource1 = mCache.insert(key1, WriterCallbacks.from(value1));

  verifyListenerOnWriteAttempt(key1);
  String resourceId1 = verifyListenerOnWriteSuccessAndGetResourceId(key1, value1Size);

  BinaryResource resource1Again = mCache.getResource(key1);
  assertEquals(resource1, resource1Again);
  verifyListenerOnHit(key1, resourceId1);

  BinaryResource resource1Again2 = mCache.getResource(key1);
  assertEquals(resource1, resource1Again2);
  verifyListenerOnHit(key1, resourceId1);

  SimpleCacheKey missingKey = new SimpleCacheKey("nonexistent_key");
  BinaryResource res2 = mCache.getResource(missingKey);
  assertNull(res2);
  verifyListenerOnMiss(missingKey);

  mCache.clearAll();
  verify(mCacheEventListener).onCleared();

  verifyNoMoreInteractions(mCacheEventListener);
}
 
Example #15
Source File: DiskStorageCache.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
public boolean hasKey(final CacheKey key) {
  try {
    return mStorageSupplier.get().contains(getResourceId(key), key);
  } catch (IOException e) {
    return false;
  }
}
 
Example #16
Source File: BufferedDiskCache.java    From fresco with MIT License 5 votes vote down vote up
/**
 * Performs disk cache check synchronously.
 *
 * @param key
 * @return true if the key is found in disk cache else false
 */
public boolean diskCheckSync(final CacheKey key) {
  if (containsSync(key)) {
    return true;
  }
  return checkInStagingAreaAndFileCache(key);
}
 
Example #17
Source File: ImagePipeline.java    From fresco with MIT License 5 votes vote down vote up
/**
 * Performs disk cache check synchronously. It is not recommended to use this unless you know what
 * exactly you are doing. Disk cache check is a costly operation, the call will block the caller
 * thread until the cache check is completed.
 *
 * @param imageRequest the imageRequest for the image to be looked up.
 * @return true if the image was found in the disk cache, false otherwise.
 */
public boolean isInDiskCacheSync(final ImageRequest imageRequest) {
  final CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest, null);
  final ImageRequest.CacheChoice cacheChoice = imageRequest.getCacheChoice();

  switch (cacheChoice) {
    case DEFAULT:
      return mMainBufferedDiskCache.diskCheckSync(cacheKey);
    case SMALL:
      return mSmallImageBufferedDiskCache.diskCheckSync(cacheKey);
    default:
      return false;
  }
}
 
Example #18
Source File: HueBlendPostProcessor.java    From react-native-image-filter-kit with MIT License 5 votes vote down vote up
public HueBlendPostProcessor(
  final int width,
  final int height,
  final @Nullable JSONObject config,
  final @Nonnull CloseableReference<CloseableImage> src,
  final @Nonnull CacheKey srcCacheKey,
  final @Nonnull Context context
) {
  super(width, height, config, src, srcCacheKey, context);
}
 
Example #19
Source File: BufferedDiskCache.java    From fresco with MIT License 5 votes vote down vote up
/** Removes the item from the disk cache and the staging area. */
public Task<Void> remove(final CacheKey key) {
  Preconditions.checkNotNull(key);
  mStagingArea.remove(key);
  try {
    final Object token = FrescoInstrumenter.onBeforeSubmitWork("BufferedDiskCache_remove");
    return Task.call(
        new Callable<Void>() {
          @Override
          public Void call() throws Exception {
            final Object currentToken = FrescoInstrumenter.onBeginWork(token, null);
            try {
              mStagingArea.remove(key);
              mFileCache.remove(key);
            } catch (Throwable th) {
              FrescoInstrumenter.markFailure(token, th);
              throw th;
            } finally {
              FrescoInstrumenter.onEndWork(currentToken);
            }
            return null;
          }
        },
        mWriteExecutor);
  } catch (Exception exception) {
    // Log failure
    // TODO: 3697790
    FLog.w(TAG, exception, "Failed to schedule disk-cache remove for %s", key.getUriString());
    return Task.forError(exception);
  }
}
 
Example #20
Source File: ImagePipelineFactory.java    From fresco with MIT License 5 votes vote down vote up
public InstrumentedMemoryCache<CacheKey, PooledByteBuffer> getEncodedMemoryCache() {
  if (mEncodedMemoryCache == null) {
    MemoryCache<CacheKey, PooledByteBuffer> backingCache =
        mConfig.getEncodedMemoryCacheOverride() != null
            ? mConfig.getEncodedMemoryCacheOverride()
            : getEncodedCountingMemoryCache();
    mEncodedMemoryCache =
        EncodedMemoryCacheFactory.get(backingCache, mConfig.getImageCacheStatsTracker());
  }
  return mEncodedMemoryCache;
}
 
Example #21
Source File: SourceInCompositingPostProcessor.java    From react-native-image-filter-kit with MIT License 5 votes vote down vote up
public SourceInCompositingPostProcessor(
  final int width,
  final int height,
  final @Nullable JSONObject config,
  final @Nonnull CloseableReference<CloseableImage> src,
  final @Nonnull CacheKey srcCacheKey,
  final @Nonnull Context context
) {
  super(width, height, config, src, srcCacheKey, context);
}
 
Example #22
Source File: RenderscriptCompositionPostProcessor.java    From react-native-image-filter-kit with MIT License 5 votes vote down vote up
public RenderscriptCompositionPostProcessor(
  int width,
  int height,
  @Nullable JSONObject config,
  @Nonnull CloseableReference<CloseableImage> src,
  @Nonnull CacheKey srcCacheKey,
  @Nonnull Context context
) {
  super(width, height, config, src, srcCacheKey);

  mContext = context;
}
 
Example #23
Source File: SmoothSweepGradientPostProcessor.java    From react-native-image-filter-kit with MIT License 5 votes vote down vote up
@Nonnull
@Override
public CacheKey generateCacheKey() {
  return new SimpleCacheKey(String.format(
    Locale.ROOT,
    "smooth_sweep_gradient_%d_%d_%f_%f_%s_%s",
    mWidth,
    mHeight,
    mCx,
    mCy,
    Arrays.toString(mColors),
    Arrays.toString(mPositions)
  ));
}
 
Example #24
Source File: DestinationATopCompositingPostProcessor.java    From react-native-image-filter-kit with MIT License 5 votes vote down vote up
public DestinationATopCompositingPostProcessor(
  final int width,
  final int height,
  final @Nullable JSONObject config,
  final @Nonnull CloseableReference<CloseableImage> src,
  final @Nonnull CacheKey srcCacheKey,
  final @Nonnull Context context
) {
  super(width, height, config, src, srcCacheKey, context);
}
 
Example #25
Source File: DiskStorageCacheTest.java    From fresco with MIT License 5 votes vote down vote up
private void verifyListenerOnReadException(CacheKey key, IOException exception) {
  ArgumentCaptor<CacheEvent> cacheEventCaptor = ArgumentCaptor.forClass(CacheEvent.class);
  mCacheEventListenerInOrder
      .verify(mCacheEventListener)
      .onReadException(cacheEventCaptor.capture());

  CacheEventAssert.assertThat(cacheEventCaptor.getValue())
      .isNotNull()
      .hasCacheKey(key)
      .hasException(exception);
}
 
Example #26
Source File: ColorMatrixColorFilterPostProcessor.java    From react-native-image-filter-kit with MIT License 5 votes vote down vote up
@Nonnull
@Override
public CacheKey generateCacheKey() {
  return new SimpleCacheKey(String.format(
    Locale.ROOT,
    "color_matrix_color_filter_%s",
    Arrays.toString(mMatrix)
  ));
}
 
Example #27
Source File: SweepGradientPostProcessor.java    From react-native-image-filter-kit with MIT License 5 votes vote down vote up
@Nonnull
@Override
public CacheKey generateCacheKey() {
  return new SimpleCacheKey(String.format(
    Locale.ROOT,
    "sweep_gradient_%d_%d_%f_%f_%s_%s",
    mWidth,
    mHeight,
    mCx,
    mCy,
    Arrays.toString(mColors),
    Arrays.toString(mPositions)
  ));
}
 
Example #28
Source File: DiskStorageCacheTest.java    From fresco with MIT License 5 votes vote down vote up
@Test
public void testHasKeyWithoutPopulateAtStartupWithAwaitingIndex() throws Exception {
  // A new cache object in the same directory. Equivalent to a process restart.
  // Index may not yet updated.
  DiskStorageCache cache2 = createDiskCache(mStorage, false);
  CacheKey key = putOneThingInCache();
  // Wait for index populated in cache before use of cache
  cache2.awaitIndex();
  assertTrue(cache2.isIndexReady());
  assertTrue(cache2.hasKey(key));
  assertTrue(cache2.hasKeySync(key));
}
 
Example #29
Source File: ScriptIntrinsicConvolve5x5PostProcessor.java    From react-native-image-filter-kit with MIT License 5 votes vote down vote up
@Nonnull
@Override
public CacheKey generateCacheKey() {
  return new SimpleCacheKey(String.format(
    Locale.ROOT,
    "script_intrinsic_convolve_5x5_%s",
    Arrays.toString(mCoefficients))
  );
}
 
Example #30
Source File: DiskStorageCacheTest.java    From fresco with MIT License 5 votes vote down vote up
private void verifyListenerOnMiss(CacheKey key) {
  ArgumentCaptor<CacheEvent> cacheEventCaptor = ArgumentCaptor.forClass(CacheEvent.class);
  mCacheEventListenerInOrder.verify(mCacheEventListener).onMiss(cacheEventCaptor.capture());

  for (CacheEvent event : cacheEventCaptor.getAllValues()) {
    CacheEventAssert.assertThat(event).isNotNull().hasCacheKey(key);
  }
}