/*
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

package com.facebook.drawee.backends.volley;

import android.graphics.Bitmap;
import android.net.Uri;

import com.facebook.datasource.AbstractDataSource;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.controller.AbstractDraweeControllerBuilder;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;

/**
 * {@link DataSource} that wraps Volley {@link ImageLoader}.
 */
public class VolleyDataSource extends AbstractDataSource<Bitmap> {
  private ImageLoader.ImageContainer mImageContainer;

  public VolleyDataSource(
      final ImageLoader imageLoader,
      final Uri imageRequest,
      final AbstractDraweeControllerBuilder.CacheLevel cacheLevel) {

    String uriString = imageRequest.toString();
    int maxWidth = 0;
    int maxHeight = 0;

    if (cacheLevel != AbstractDraweeControllerBuilder.CacheLevel.FULL_FETCH) {
      if (!imageLoader.isCached(uriString, maxWidth, maxHeight)) {
        mImageContainer = null;
        setFailure(new NullPointerException("Image not found in bitmap-cache."));
        return;
      }
    }

    mImageContainer = imageLoader.get(
        uriString,
        new ImageLoader.ImageListener() {
          @Override
          public void onErrorResponse(VolleyError error) {
            setFailure(error.getCause());
          }
          @Override
          public void onResponse(final ImageLoader.ImageContainer response, boolean isImmediate) {
            if (response.getBitmap() != null) {
              setResult(response.getBitmap(), true);
            }
          }
        },
        maxWidth,
        maxHeight);
  }

  @Override
  public boolean close() {
    if (mImageContainer != null) {
      mImageContainer.cancelRequest();
    }
    return super.close();
  }
}

@@ -403,16 +403,69 @@
 net.Uri;
+%0Aimport android.os.Handler;%0Aimport android.os.Looper;
 %0A%0Aimport
@@ -847,16 +847,88 @@
 tmap%3E %7B%0A
+  private final Handler mHandler = new Handler(Looper.getMainLooper());%0A
   privat
@@ -2140,38 +2140,259 @@
     
-mImageContainer.cancelRequest(
+// Prevent ConcurrentModificationException in Volley%0A      mHandler.post(new Runnable() %7B%0A        @Override%0A        public void run() %7B%0A          if (mImageContainer != null) %7B%0A            mImageContainer.cancelRequest();%0A          %7D%0A        %7D%0A      %7D
 );%0A 

Prevent ConcurrentModificationException in Volley