Java Code Examples for com.facebook.common.internal.Preconditions

The following examples show how to use com.facebook.common.internal.Preconditions. These examples are extracted from open source projects. 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
/**
 * Reads up to MAX_HEADER_LENGTH bytes from is InputStream. If mark is supported by is, it is
 * used to restore content of the stream after appropriate amount of data is read.
 * Read bytes are stored in imageHeaderBytes, which should be capable of storing
 * MAX_HEADER_LENGTH bytes.
 * @param is
 * @param imageHeaderBytes
 * @return number of bytes read from is
 * @throws IOException
 */
private static int readHeaderFromStream(
    final InputStream is,
    final byte[] imageHeaderBytes)
    throws IOException {
  Preconditions.checkNotNull(is);
  Preconditions.checkNotNull(imageHeaderBytes);
  Preconditions.checkArgument(imageHeaderBytes.length >= MAX_HEADER_LENGTH);

  // If mark is supported by the stream, use it to let the owner of the stream re-read the same
  // data. Otherwise, just consume some data.
  if (is.markSupported()) {
    try {
      is.mark(MAX_HEADER_LENGTH);
      return ByteStreams.read(is, imageHeaderBytes, 0, MAX_HEADER_LENGTH);
    } finally {
      is.reset();
    }
  } else {
    return ByteStreams.read(is, imageHeaderBytes, 0, MAX_HEADER_LENGTH);
  }
}
 
Example 2
Source Project: fresco   Source File: Bucket.java    License: MIT License 6 votes vote down vote up
/**
 * Releases a value to this bucket and decrements the inUse count
 *
 * @param value the value to release
 */
public void release(V value) {
  Preconditions.checkNotNull(value);
  if (mFixBucketsReinitialization) {
    // Proper way
    Preconditions.checkState(mInUseLength > 0);
    mInUseLength--;
    addToFreeList(value);
  } else {
    // Keep using previous adhoc
    if (mInUseLength > 0) {
      mInUseLength--;
      addToFreeList(value);
    } else {
      FLog.e(TAG, "Tried to release value %s from an empty bucket!", value);
    }
  }
}
 
Example 3
Source Project: fresco   Source File: BitmapUtil.java    License: MIT License 6 votes vote down vote up
/**
 * Decodes the bounds of an image and returns its width and height or null if the size can't be
 * determined
 *
 * @param is the InputStream containing the image data
 * @return dimensions of the image
 */
public static @Nullable Pair<Integer, Integer> decodeDimensions(InputStream is) {
  Preconditions.checkNotNull(is);
  ByteBuffer byteBuffer = DECODE_BUFFERS.acquire();
  if (byteBuffer == null) {
    byteBuffer = ByteBuffer.allocate(DECODE_BUFFER_SIZE);
  }
  BitmapFactory.Options options = new BitmapFactory.Options();
  options.inJustDecodeBounds = true;
  try {
    options.inTempStorage = byteBuffer.array();
    BitmapFactory.decodeStream(is, null, options);

    return (options.outWidth == -1 || options.outHeight == -1)
        ? null
        : new Pair<>(options.outWidth, options.outHeight);
  } finally {
    DECODE_BUFFERS.release(byteBuffer);
  }
}
 
Example 4
@Override
public void onAttach() {
  if (FLog.isLoggable(FLog.VERBOSE)) {
    FLog.v(
        TAG,
        "controller %x %s: onAttach: %s",
        System.identityHashCode(this),
        mId,
        mIsRequestSubmitted ? "request already submitted" : "request needs submit");
  }
  mEventTracker.recordEvent(Event.ON_ATTACH_CONTROLLER);
  Preconditions.checkNotNull(mSettableDraweeHierarchy);
  mDeferredReleaser.cancelDeferredRelease(this);
  mIsAttached = true;
  if (!mIsRequestSubmitted) {
    submitRequest();
  }
}
 
Example 5
Source Project: fresco   Source File: AshmemMemoryChunk.java    License: MIT License 6 votes vote down vote up
/**
 * This does actual copy. It should be called only when we hold locks on both this and other
 * objects
 */
private void doCopy(
    final int offset, final MemoryChunk other, final int otherOffset, final int count) {
  if (!(other instanceof AshmemMemoryChunk)) {
    throw new IllegalArgumentException("Cannot copy two incompatible MemoryChunks");
  }
  Preconditions.checkState(!isClosed());
  Preconditions.checkState(!other.isClosed());
  MemoryChunkUtil.checkBounds(offset, other.getSize(), otherOffset, count, getSize());
  mByteBuffer.position(offset);
  // ByteBuffer can't be null at this point
  other.getByteBuffer().position(otherOffset);
  // Recover the necessary part to be copied as a byte array.
  // This requires a copy, for now there is not a more efficient alternative.
  byte[] b = new byte[count];
  mByteBuffer.get(b, 0, count);
  other.getByteBuffer().put(b, 0, count);
}
 
Example 6
Source Project: fresco   Source File: PoolParams.java    License: MIT License 6 votes vote down vote up
/**
 * Set up pool params
 *
 * @param maxSizeSoftCap soft cap on max size of the pool
 * @param maxSizeHardCap hard cap on max size of the pool
 * @param bucketSizes (optional) bucket sizes and lengths for the pool
 * @param minBucketSize min bucket size for the pool
 * @param maxBucketSize max bucket size for the pool
 * @param maxNumThreads the maximum number of threads in the pool, or -1 if the pool doesn't care
 */
public PoolParams(
    int maxSizeSoftCap,
    int maxSizeHardCap,
    @Nullable SparseIntArray bucketSizes,
    int minBucketSize,
    int maxBucketSize,
    int maxNumThreads) {
  Preconditions.checkState(maxSizeSoftCap >= 0 && maxSizeHardCap >= maxSizeSoftCap);
  this.maxSizeSoftCap = maxSizeSoftCap;
  this.maxSizeHardCap = maxSizeHardCap;
  this.bucketSizes = bucketSizes;
  this.minBucketSize = minBucketSize;
  this.maxBucketSize = maxBucketSize;
  this.maxNumThreads = maxNumThreads;
}
 
Example 7
Source Project: fresco   Source File: AbstractDraweeController.java    License: MIT License 6 votes vote down vote up
/** Adds controller listener. */
public void addControllerListener(ControllerListener<? super INFO> controllerListener) {
  Preconditions.checkNotNull(controllerListener);
  if (mControllerListener instanceof InternalForwardingListener) {
    ((InternalForwardingListener<INFO>) mControllerListener).addListener(controllerListener);
    return;
  }
  if (mControllerListener != null) {
    mControllerListener =
        InternalForwardingListener.createInternal(mControllerListener, controllerListener);
    return;
  }
  // Listener only receives <INFO>, it never produces one.
  // That means if it can accept <? super INFO>, it can very well accept <INFO>.
  mControllerListener = (ControllerListener<INFO>) controllerListener;
}
 
Example 8
/**
 * Skips exactly bytesCount bytes in inputStream unless end of stream is reached first.
 *
 * @param inputStream input stream to skip bytes from
 * @param bytesCount number of bytes to skip
 * @return number of skipped bytes
 * @throws IOException
 */
public static long skip(final InputStream inputStream, final long bytesCount) throws IOException {
  Preconditions.checkNotNull(inputStream);
  Preconditions.checkArgument(bytesCount >= 0);

  long toSkip = bytesCount;
  while (toSkip > 0) {
    final long skipped = inputStream.skip(toSkip);
    if (skipped > 0) {
      toSkip -= skipped;
      continue;
    }

    if (inputStream.read() != -1) {
      toSkip--;
      continue;
    }
    return bytesCount - toSkip;
  }

  return bytesCount;
}
 
Example 9
Source Project: fresco   Source File: StreamUtil.java    License: MIT License 6 votes vote down vote up
/**
 * Skips exactly bytesCount bytes in inputStream unless end of stream is reached first.
 *
 * @param inputStream input stream to skip bytes from
 * @param bytesCount number of bytes to skip
 * @return number of skipped bytes
 * @throws IOException
 */
public static long skip(final InputStream inputStream, final long bytesCount) throws IOException {
  Preconditions.checkNotNull(inputStream);
  Preconditions.checkArgument(bytesCount >= 0);

  long toSkip = bytesCount;
  while (toSkip > 0) {
    final long skipped = inputStream.skip(toSkip);
    if (skipped > 0) {
      toSkip -= skipped;
      continue;
    }

    if (inputStream.read() != -1) {
      toSkip--;
      continue;
    }
    return bytesCount - toSkip;
  }

  return bytesCount;
}
 
Example 10
Source Project: fresco   Source File: GingerbreadPurgeableDecoder.java    License: MIT License 6 votes vote down vote up
private Bitmap decodeFileDescriptorAsPurgeable(
    CloseableReference<PooledByteBuffer> bytesRef,
    int inputLength,
    byte[] suffix,
    BitmapFactory.Options options) {
  MemoryFile memoryFile = null;
  try {
    memoryFile = copyToMemoryFile(bytesRef, inputLength, suffix);
    FileDescriptor fd = getMemoryFileDescriptor(memoryFile);
    if (mWebpBitmapFactory != null) {
      Bitmap bitmap = mWebpBitmapFactory.decodeFileDescriptor(fd, null, options);
      return Preconditions.checkNotNull(bitmap, "BitmapFactory returned null");
    } else {
      throw new IllegalStateException("WebpBitmapFactory is null");
    }
  } catch (IOException e) {
    throw Throwables.propagate(e);
  } finally {
    if (memoryFile != null) {
      memoryFile.close();
    }
  }
}
 
Example 11
Source Project: fresco   Source File: ArrayDrawable.java    License: MIT License 6 votes vote down vote up
/** Sets a new drawable at the specified index, and return the previous drawable, if any. */
@Nullable
public Drawable setDrawable(int index, @Nullable Drawable drawable) {
  Preconditions.checkArgument(index >= 0);
  Preconditions.checkArgument(index < mLayers.length);
  final Drawable oldDrawable = mLayers[index];
  if (drawable != oldDrawable) {
    if (drawable != null && mIsMutated) {
      drawable.mutate();
    }

    DrawableUtils.setCallbacks(mLayers[index], null, null);
    DrawableUtils.setCallbacks(drawable, null, null);
    DrawableUtils.setDrawableProperties(drawable, mDrawableProperties);
    DrawableUtils.copyProperties(drawable, this);
    DrawableUtils.setCallbacks(drawable, this, this);
    mIsStatefulCalculated = false;
    mLayers[index] = drawable;
    invalidateSelf();
  }
  return oldDrawable;
}
 
Example 12
Source Project: fresco   Source File: CountingMemoryCache.java    License: MIT License 6 votes vote down vote up
/**
 * Gets the value with the given key to be reused, or null if there is no such value.
 *
 * <p>The item can be reused only if it is exclusively owned by the cache.
 */
@Nullable
public CloseableReference<V> reuse(K key) {
  Preconditions.checkNotNull(key);
  CloseableReference<V> clientRef = null;
  boolean removed = false;
  Entry<K, V> oldExclusive = null;
  synchronized (this) {
    oldExclusive = mExclusiveEntries.remove(key);
    if (oldExclusive != null) {
      Entry<K, V> entry = mCachedEntries.remove(key);
      Preconditions.checkNotNull(entry);
      Preconditions.checkState(entry.clientCount == 0);
      // optimization: instead of cloning and then closing the original reference,
      // we just do a move
      clientRef = entry.valueRef;
      removed = true;
    }
  }
  if (removed) {
    maybeNotifyExclusiveEntryRemoval(oldExclusive);
  }
  return clientRef;
}
 
Example 13
Source Project: fresco   Source File: ArrayDrawable.java    License: MIT License 5 votes vote down vote up
/** Gets the {@code DrawableParent} for index. */
public DrawableParent getDrawableParentForIndex(int index) {
  Preconditions.checkArgument(index >= 0);
  Preconditions.checkArgument(index < mDrawableParents.length);
  if (mDrawableParents[index] == null) {
    mDrawableParents[index] = createDrawableParentForIndex(index);
  }
  return mDrawableParents[index];
}
 
Example 14
Source Project: ImageLoadPK   Source File: WatchImageView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setImageDrawable(Drawable drawable) {

    Preconditions.checkNotNull(drawable);
    if (drawable == Drawables.sPlaceholderDrawable) {
        //不再这里调用,在初始化加载器,Glide.build()实现调用更好
    } else if (drawable == Drawables.sErrorDrawable) {
        mWatcher.onFailure();//加载失败
    } else {
        mWatcher.onSuccess();//加载成功
    }
    super.setImageDrawable(drawable);
}
 
Example 15
Source Project: fresco   Source File: BufferMemoryChunk.java    License: MIT License 5 votes vote down vote up
@Override
public synchronized int write(
    final int memoryOffset, final byte[] byteArray, final int byteArrayOffset, final int count) {
  Preconditions.checkNotNull(byteArray);
  Preconditions.checkState(!isClosed());
  final int actualCount = MemoryChunkUtil.adjustByteCount(memoryOffset, count, mSize);
  MemoryChunkUtil.checkBounds(
      memoryOffset, byteArray.length, byteArrayOffset, actualCount, mSize);
  mBuffer.position(memoryOffset);
  mBuffer.put(byteArray, byteArrayOffset, actualCount);
  return actualCount;
}
 
Example 16
Source Project: fresco   Source File: BitmapPrepareProducer.java    License: MIT License 5 votes vote down vote up
/**
 * @param inputProducer The next producer in the pipeline
 * @param minBitmapSizeBytes Bitmaps with a {@link Bitmap#getByteCount()} smaller than this value
 *     are not uploaded
 * @param maxBitmapSizeBytes Bitmaps with a {@link Bitmap#getByteCount()} larger than this value
 *     are not uploaded
 */
public BitmapPrepareProducer(
    final Producer<CloseableReference<CloseableImage>> inputProducer,
    int minBitmapSizeBytes,
    int maxBitmapSizeBytes,
    boolean preparePrefetch) {
  Preconditions.checkArgument(minBitmapSizeBytes <= maxBitmapSizeBytes);
  mInputProducer = Preconditions.checkNotNull(inputProducer);
  mMinBitmapSizeBytes = minBitmapSizeBytes;
  mMaxBitmapSizeBytes = maxBitmapSizeBytes;
  mPreparePrefetch = preparePrefetch;
}
 
Example 17
Source Project: fresco   Source File: Instrumentation.java    License: MIT License 5 votes vote down vote up
public void onFailure() {
  Preconditions.checkState(mState == ImageRequestState.STARTED);
  mState = ImageRequestState.FAILURE;
  mFinishTime = System.currentTimeMillis();
  final long elapsedTime = mFinishTime - mStartTime;
  mPerfListener.reportFailure(elapsedTime);
  FLog.i(TAG, "Image [%s]: failed after %d ms", mTag, elapsedTime);
}
 
Example 18
Source Project: fresco   Source File: Instrumentation.java    License: MIT License 5 votes vote down vote up
public void onSuccess() {
  Preconditions.checkState(mState == ImageRequestState.STARTED);
  mState = ImageRequestState.SUCCESS;
  mFinishTime = System.currentTimeMillis();
  final long elapsedTime = mFinishTime - mStartTime;
  mPerfListener.reportSuccess(elapsedTime);
  FLog.i(TAG, "Image [%s]: loaded after %d ms", mTag, elapsedTime);
}
 
Example 19
Source Project: fresco   Source File: DefaultDiskStorage.java    License: MIT License 5 votes vote down vote up
private boolean isExpectedFile(File file) {
  FileInfo info = getShardFileInfo(file);
  if (info == null) {
    return false;
  }
  if (info.type == FileType.TEMP) {
    return isRecentFile(file);
  }
  Preconditions.checkState(info.type == FileType.CONTENT);
  return true;
}
 
Example 20
Source Project: fresco   Source File: RoundedDrawable.java    License: MIT License 5 votes vote down vote up
/**
 * Specify radius for the corners of the rectangle. If this is > 0, then the drawable is drawn in
 * a round-rectangle, rather than a rectangle.
 *
 * @param radius the radius for the corners of the rectangle
 */
@Override
public void setRadius(float radius) {
  Preconditions.checkState(radius >= 0);
  Arrays.fill(mCornerRadii, radius);
  mRadiiNonZero = (radius != 0);
  mIsPathDirty = true;
  invalidateSelf();
}
 
Example 21
private void validate() {
  if (mOverlays != null) {
    for (Drawable overlay : mOverlays) {
      Preconditions.checkNotNull(overlay);
    }
  }

  if (mBackgrounds != null) {
    for (Drawable background : mBackgrounds) {
      Preconditions.checkNotNull(background);
    }
  }
}
 
Example 22
public static <T> ListDataSource<T> create(
    DataSource<CloseableReference<T>>... dataSources) {
  Preconditions.checkNotNull(dataSources);
  Preconditions.checkState(dataSources.length > 0);
  ListDataSource<T> listDataSource = new ListDataSource<T>(dataSources);
  for (DataSource<CloseableReference<T>> dataSource : dataSources) {
    dataSource.subscribe(
        listDataSource.new InternalDataSubscriber(),
        CallerThreadExecutor.getInstance());
  }
  return listDataSource;
}
 
Example 23
/**
 * Decrements reference count for the shared reference. Returns value of mRefCount after
 * decrementing
 */
private synchronized int decreaseRefCount() {
  ensureValid();
  Preconditions.checkArgument(mRefCount > 0);

  mRefCount--;
  return mRefCount;
}
 
Example 24
Source Project: fresco   Source File: DownsampleUtil.java    License: MIT License 5 votes vote down vote up
@VisibleForTesting
public static float determineDownsampleRatio(
    final RotationOptions rotationOptions,
    @Nullable final ResizeOptions resizeOptions,
    final EncodedImage encodedImage) {
  Preconditions.checkArgument(EncodedImage.isMetaDataAvailable(encodedImage));
  if (resizeOptions == null
      || resizeOptions.height <= 0
      || resizeOptions.width <= 0
      || encodedImage.getWidth() == 0
      || encodedImage.getHeight() == 0) {
    return 1.0f;
  }

  final int rotationAngle = getRotationAngle(rotationOptions, encodedImage);
  final boolean swapDimensions = rotationAngle == 90 || rotationAngle == 270;
  final int widthAfterRotation =
      swapDimensions ? encodedImage.getHeight() : encodedImage.getWidth();
  final int heightAfterRotation =
      swapDimensions ? encodedImage.getWidth() : encodedImage.getHeight();

  final float widthRatio = ((float) resizeOptions.width) / widthAfterRotation;
  final float heightRatio = ((float) resizeOptions.height) / heightAfterRotation;
  float ratio = Math.max(widthRatio, heightRatio);
  FLog.v(
      "DownsampleUtil",
      "Downsample - Specified size: %dx%d, image size: %dx%d "
          + "ratio: %.1f x %.1f, ratio: %.3f",
      resizeOptions.width,
      resizeOptions.height,
      widthAfterRotation,
      heightAfterRotation,
      widthRatio,
      heightRatio,
      ratio);
  return ratio;
}
 
Example 25
private ActivityListener getListenerOrCleanUp(Activity activity) {
  ActivityListener activityVisibilityListener = mActivityListenerRef.get();
  if (activityVisibilityListener == null) {
    Preconditions.checkArgument(activity instanceof ListenableActivity);
    ListenableActivity listenableActivity = (ListenableActivity) activity;
    listenableActivity.removeActivityListener(this);
  }
  return activityVisibilityListener;
}
 
Example 26
Source Project: fresco   Source File: DraweeHolder.java    License: MIT License 5 votes vote down vote up
/** Sets the drawee hierarchy. */
public void setHierarchy(DH hierarchy) {
  mEventTracker.recordEvent(Event.ON_SET_HIERARCHY);
  final boolean isControllerValid = isControllerValid();

  setVisibilityCallback(null);
  mHierarchy = Preconditions.checkNotNull(hierarchy);
  Drawable drawable = mHierarchy.getTopLevelDrawable();
  onVisibilityChange(drawable == null || drawable.isVisible());
  setVisibilityCallback(this);

  if (isControllerValid) {
    mController.setHierarchy(hierarchy);
  }
}
 
Example 27
Source Project: fresco   Source File: BasePoolTest.java    License: MIT License 5 votes vote down vote up
private static SparseIntArray makeBucketSizeArray(int... params) {
  Preconditions.checkArgument(params.length % 2 == 0);
  final SparseIntArray bucketSizes = new SparseIntArray();
  for (int i = 0; i < params.length; i += 2) {
    bucketSizes.append(params[i], params[i + 1]);
  }
  return bucketSizes;
}
 
Example 28
Source Project: fresco   Source File: RenderScriptBlurFilter.java    License: MIT License 5 votes vote down vote up
/**
 * Not-in-place intrinsic Gaussian blur filter using {@link ScriptIntrinsicBlur} and {@link
 * RenderScript}. This require an Android versions >= 4.2.
 *
 * @param dest The {@link Bitmap} where the blurred image is written to.
 * @param src The {@link Bitmap} containing the original image.
 * @param context The {@link Context} necessary to use {@link RenderScript}
 * @param radius The radius of the blur with a supported range 0 < radius <= {@link
 *     #BLUR_MAX_RADIUS}
 */
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static void blurBitmap(
    final Bitmap dest, final Bitmap src, final Context context, final int radius) {
  Preconditions.checkNotNull(dest);
  Preconditions.checkNotNull(src);
  Preconditions.checkNotNull(context);
  Preconditions.checkArgument(radius > 0 && radius <= BLUR_MAX_RADIUS);
  RenderScript rs = null;
  try {
    rs = RenderScript.create(context);

    // Create an Intrinsic Blur Script using the Renderscript
    ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));

    // Create the input/output allocations with Renderscript and the src/dest bitmaps
    Allocation allIn = Allocation.createFromBitmap(rs, src);
    Allocation allOut = Allocation.createFromBitmap(rs, dest);

    // Set the radius of the blur
    blurScript.setRadius(radius);
    blurScript.setInput(allIn);
    blurScript.forEach(allOut);
    allOut.copyTo(dest);

    blurScript.destroy();
    allIn.destroy();
    allOut.destroy();
  } finally {
    if (rs != null) {
      rs.destroy();
    }
  }
}
 
Example 29
/**
 * Caches given key value pair. After this method returns, caller should use returned instance
 * of CloseableReference, which depending on implementation might or might not be the same as
 * the one provided by caller. Caller is responsible for calling release method to notify
 * cache that cached value won't be used anymore. This allows the cache to maintain value's
 * in-use count.
 */
public CloseableReference<V> cache(final K key, final CloseableReference<V> value) {
  Preconditions.checkNotNull(key);
  Preconditions.checkNotNull(value);

  maybeUpdateCacheParams();
  /**
   * We might be required to remove old entry associated with the same key.
   */
  CloseableReference<V> removedValue = null;
  CacheEntry<K, V> newCacheEntry = null;

  synchronized (this) {
    if (!canCacheNewValue(value)) {
      return null;
    }

    newCacheEntry = CacheEntry.of(key, value.clone());
    removedValue = handleIndexRegistration(key, newCacheEntry.value);
    putInCachedEntries(newCacheEntry);
    increaseUsageCount(newCacheEntry);
  }

  if (removedValue != null) {
    removedValue.close();
  }

  maybeEvictEntries();

  return newCacheEntry.value;
}
 
Example 30
/**
 * Copy bytes from native memory to byte array.
 * @param nativeMemoryOffset number of first byte to copy
 * @param byteArray byte array to copy to
 * @param byteArrayOffset number of first byte in byte array to be written
 * @param count number of bytes to copy
 * @return number of bytes read
 */
public synchronized int read(
    final int nativeMemoryOffset,
    final byte[] byteArray,
    final int byteArrayOffset,
    final int count) {
  Preconditions.checkNotNull(byteArray);
  Preconditions.checkState(!isClosed());
  final int actualCount = adjustByteCount(nativeMemoryOffset, count);
  checkBounds(nativeMemoryOffset, byteArray.length, byteArrayOffset, actualCount);
  nativeCopyToByteArray(mNativePtr + nativeMemoryOffset, byteArray, byteArrayOffset, actualCount);
  return actualCount;
}