com.bumptech.glide.Priority

Here are the examples of the java api com.bumptech.glide.Priority taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

52 Examples 7

19 Source : GlideVFSLoader.java
with Apache License 2.0
from zom

@Override
public void loadData(Priority priority, DataCallback<? super InputStream> callback) {
    callback.onDataReady(vfsFileStream);
}

19 Source : CommonDataFetcher.java
with Apache License 2.0
from zixpo

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super Bitmap> callback) {
    if (mModel.startsWith("drawable://")) {
        callback.onDataReady(getDrawable(mModel));
    } else if (mModel.startsWith("package://")) {
        callback.onDataReady(getPackage(mModel));
    }
}

19 Source : AttachmentStreamLocalUriFetcher.java
with GNU General Public License v3.0
from XecureIT

@Override
public void loadData(Priority priority, DataCallback<? super InputStream> callback) {
    try {
        if (!digest.isPresent())
            throw new InvalidMessageException("No attachment digest!");
        is = AttachmentCipherInputStream.createFor(attachment, plaintextLength, key, digest.get());
        callback.onDataReady(is);
    } catch (IOException | InvalidMessageException e) {
        callback.onLoadFailed(e);
    }
}

19 Source : ContactPhotoFetcher.java
with GNU General Public License v3.0
from XecureIT

@Override
public void loadData(Priority priority, DataCallback<? super InputStream> callback) {
    try {
        inputStream = contactPhoto.openInputStream(context);
        callback.onDataReady(inputStream);
    } catch (IOException e) {
        callback.onLoadFailed(e);
    }
}

19 Source : TypeFetcher.java
with GNU General Public License v3.0
from timusus

private InputStream loadData(DataFetcher<InputStream> dataFetcher, Priority priority) {
    InputStream inputStream;
    try {
        inputStream = dataFetcher.loadData(priority);
    } catch (Exception e) {
        if (dataFetcher != null) {
            dataFetcher.cleanup();
        }
        inputStream = null;
    }
    return inputStream;
}

19 Source : TypeFetcher.java
with GNU General Public License v3.0
from timusus

@Override
public InputStream loadData(Priority priority) throws Exception {
    switch(type) {
        case ArtworkProvider.Type.MEDIA_STORE:
            dataFetcher = new MediaStoreFetcher(applicationContext, artworkProvider);
            break;
        case ArtworkProvider.Type.FOLDER:
            dataFetcher = new FolderFetcher(artworkProvider, file);
            break;
        case ArtworkProvider.Type.TAG:
            dataFetcher = new TagFetcher(artworkProvider);
            break;
        case ArtworkProvider.Type.REMOTE:
            dataFetcher = new RemoteFetcher(artworkProvider);
            break;
    }
    return loadData(dataFetcher, priority);
}

19 Source : BaseFetcher.java
with GNU General Public License v3.0
from timusus

@Override
public InputStream loadData(Priority priority) throws Exception {
    stream = getStream();
    return stream;
}

19 Source : ArtistArtDataFetcher.java
with GNU General Public License v3.0
from rasheedsulayman

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
    if (SlamUtils.canAutoDownloadArtworks(context)) {
        ArtistImageUtil.fetchArtistImageUrl(lastFmService, artistImage.artistName, url -> {
            if (isCancelled || TextUtils.isEmpty(url)) {
                callback.onDataReady(null);
                return;
            }
            GlideUrl glideUrl = new GlideUrl(url);
            // noinspection ConstantConditions
            okHttpUrlFetcher = okHttpUrlLoader.buildLoadData(glideUrl, width, height, options).fetcher;
            okHttpUrlFetcher.loadData(priority, new DataCallback<InputStream>() {

                @Override
                public void onDataReady(@Nullable InputStream data) {
                    callback.onDataReady(data);
                }

                @Override
                public void onLoadFailed(@NonNull Exception e) {
                    callback.onLoadFailed(e);
                }
            });
        });
    } else {
        callback.onDataReady(null);
    }
}

19 Source : ProgressDataFetcher.java
with MIT License
from qunarcorp

@Override
public InputStream loadData(Priority priority) throws Exception {
    Request request = new Request.Builder().url(url).build();
    final ProgressListener glideProgressListener = new ProgressListener() {

        @Override
        public void update(long bytesRead, long contentLength, boolean done) {
            Log.e(TAG, bytesRead + "," + contentLength + done);
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.what = 1;
                message.arg1 = (int) bytesRead;
                message.arg2 = (int) contentLength;
                handler.sendMessage(message);
            }
        }
    };
    OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder().body(new ProgressResponseBody(originalResponse.body(), glideProgressListener)).build();
        }
    }).build();
    try {
        progressCall = client.newCall(request);
        Response response = progressCall.execute();
        if (isCancelled) {
            return null;
        }
        if (!response.isSuccessful())
            throw new IOException("Unexpected code " + response);
        stream = response.body().byteStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return stream;
}

19 Source : AttachmentStreamLocalUriFetcher.java
with GNU General Public License v3.0
from mollyim

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
    try {
        if (!digest.isPresent())
            throw new InvalidMessageException("No attachment digest!");
        is = AttachmentCipherInputStream.createForAttachment(attachment, plaintextLength, key, digest.get());
        callback.onDataReady(is);
    } catch (IOException | InvalidMessageException e) {
        callback.onLoadFailed(e);
    }
}

19 Source : ContactPhotoFetcher.java
with GNU General Public License v3.0
from mollyim

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
    try {
        inputStream = contactPhoto.openInputStream(context);
        callback.onDataReady(inputStream);
    } catch (FileNotFoundException e) {
        callback.onDataReady(null);
    } catch (IOException e) {
        callback.onLoadFailed(e);
    }
}

19 Source : AudioFileCoverFetcher.java
with GNU General Public License v3.0
from MaxFour

@Override
public InputStream loadData(final Priority priority) throws Exception {
    final MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    try {
        retriever.setDataSource(model.filePath);
        byte[] picture = retriever.getEmbeddedPicture();
        if (picture != null) {
            stream = new ByteArrayInputStream(picture);
        } else {
            stream = AudioFileCoverUtils.fallback(model.filePath);
        }
    } finally {
        retriever.release();
    }
    return stream;
}

19 Source : PdfPicFetcher.java
with GNU General Public License v3.0
from KnIfER

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super Bitmap> callback) {
    String err = null;
    try {
        Bitmap res = model.createBitMap();
        if (res != null)
            callback.onDataReady(res);
    } catch (Exception e) {
        err = e.toString();
    }
    callback.onLoadFailed(new Exception("load mdd picture fail" + err));
}

19 Source : EngineRunnable.java
with Apache License 2.0
from guolindev

/**
 * A runnable clreplaced responsible for using an {@link DecodeJob} to decode resources on a
 * background thread in two stages.
 *
 * <p>
 *     In the first stage, this clreplaced attempts to decode a resource
 *     from cache, first using transformed data and then using source data. If no resource can be decoded from cache,
 *     this clreplaced then requests to be posted again. During the second stage this clreplaced then attempts to use the
 *     {@link DecodeJob} to decode data directly from the original source.
 * </p>
 *
 * <p>
 *     Using two stages with a re-post in between allows us to run fast disk cache decodes on one thread and slow source
 *     fetches on a second pool so that loads for local data are never blocked waiting for loads for remote data to
 *     complete.
 * </p>
 */
clreplaced EngineRunnable implements Runnable, Prioritized {

    private static final String TAG = "EngineRunnable";

    private final Priority priority;

    private final EngineRunnableManager manager;

    private final DecodeJob<?, ?, ?> decodeJob;

    private Stage stage;

    private volatile boolean isCancelled;

    public EngineRunnable(EngineRunnableManager manager, DecodeJob<?, ?, ?> decodeJob, Priority priority) {
        this.manager = manager;
        this.decodeJob = decodeJob;
        this.stage = Stage.CACHE;
        this.priority = priority;
    }

    public void cancel() {
        isCancelled = true;
        decodeJob.cancel();
    }

    @Override
    public void run() {
        if (isCancelled) {
            return;
        }
        Exception exception = null;
        Resource<?> resource = null;
        try {
            resource = decode();
        } catch (Exception e) {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Exception decoding", e);
            }
            exception = e;
        }
        if (isCancelled) {
            if (resource != null) {
                resource.recycle();
            }
            return;
        }
        if (resource == null) {
            onLoadFailed(exception);
        } else {
            onLoadComplete(resource);
        }
    }

    private boolean isDecodingFromCache() {
        return stage == Stage.CACHE;
    }

    private void onLoadComplete(Resource resource) {
        manager.onResourceReady(resource);
    }

    private void onLoadFailed(Exception e) {
        if (isDecodingFromCache()) {
            stage = Stage.SOURCE;
            manager.submitForSource(this);
        } else {
            manager.onException(e);
        }
    }

    private Resource<?> decode() throws Exception {
        if (isDecodingFromCache()) {
            return decodeFromCache();
        } else {
            return decodeFromSource();
        }
    }

    private Resource<?> decodeFromCache() throws Exception {
        Resource<?> result = null;
        try {
            result = decodeJob.decodeResultFromCache();
        } catch (Exception e) {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "Exception decoding result from cache: " + e);
            }
        }
        if (result == null) {
            result = decodeJob.decodeSourceFromCache();
        }
        return result;
    }

    private Resource<?> decodeFromSource() throws Exception {
        return decodeJob.decodeFromSource();
    }

    @Override
    public int getPriority() {
        return priority.ordinal();
    }

    private enum Stage {

        /**
         * Attempting to decode resource from cache.
         */
        CACHE,
        /**
         * Attempting to decode resource from source data.
         */
        SOURCE
    }

    interface EngineRunnableManager extends ResourceCallback {

        void submitForSource(EngineRunnable runnable);
    }
}

19 Source : MediaStoreThumbFetcher.java
with Apache License 2.0
from guolindev

@Override
public InputStream loadData(Priority priority) throws Exception {
    ThumbnailStreamOpener fetcher = factory.build(mediaStoreUri, width, height);
    if (fetcher != null) {
        inputStream = openThumbInputStream(fetcher);
    }
    if (inputStream == null) {
        inputStream = defaultFetcher.loadData(priority);
    }
    return inputStream;
}

19 Source : LocalUriFetcher.java
with Apache License 2.0
from guolindev

@Override
public final T loadData(Priority priority) throws Exception {
    ContentResolver contentResolver = context.getContentResolver();
    data = loadResource(uri, contentResolver);
    return data;
}

19 Source : ByteArrayFetcher.java
with Apache License 2.0
from guolindev

@Override
public InputStream loadData(Priority priority) {
    return new ByteArrayInputStream(bytes);
}

19 Source : AssetPathFetcher.java
with Apache License 2.0
from guolindev

@Override
public T loadData(Priority priority) throws Exception {
    data = loadResource(replacedetManager, replacedetPath);
    return data;
}

19 Source : AudioFileCoverFetcher.java
with GNU General Public License v3.0
from deepshooter

@Override
public InputStream loadData(Priority priority) throws Exception {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    try {
        retriever.setDataSource(model.filePath);
        byte[] picture = retriever.getEmbeddedPicture();
        if (picture != null) {
            return new ByteArrayInputStream(picture);
        } else {
            return fallback(model.filePath);
        }
    } finally {
        retriever.release();
    }
}

19 Source : AttachmentStreamLocalUriFetcher.java
with GNU General Public License v3.0
from CryptoGuardOSS

@Override
public InputStream loadData(Priority priority) throws Exception {
    is = new AttachmentCipherInputStream(attachment, key);
    return is;
}

19 Source : OkHttpFetcher.java
with MIT License
from CeuiLiSA

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
}

19 Source : AttachmentStreamLocalUriFetcher.java
with GNU General Public License v3.0
from CableIM

@Override
public InputStream loadData(Priority priority) throws Exception {
    is = new AttachmentCipherInputStream(attachment, key, Optional.<byte[]>absent());
    return is;
}

19 Source : PackageIconResourceDataFetcher.java
with GNU General Public License v3.0
from android-hacker

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
    try {
        data = loadResource();
    } catch (Exception e) {
        VLog.e(TAG, "Failed to load data from replacedet manager", e);
        callback.onLoadFailed(e);
        return;
    }
    callback.onDataReady(data);
}

19 Source : ArtistImageFetcher.java
with GNU General Public License v3.0
from AdrienPoupa

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
    try {
        if (!MusicUtil.isArtistNameUnknown(model.artistName) && PreferenceUtil.isAllowedToDownloadMetadata(context)) {
            call = deezerRestClient.getArtistImage(model.artistName);
            call.enqueue(new Callback<DeezerResponse>() {

                @Override
                public void onResponse(@NonNull Call<DeezerResponse> call, @NonNull Response<DeezerResponse> response) {
                    if (isCancelled) {
                        callback.onDataReady(null);
                        return;
                    }
                    try {
                        DeezerResponse deezerResponse = response.body();
                        List<Data> data = deezerResponse.getData();
                        if (data != null && data.size() > 0) {
                            String url = data.get(0).getPictureMedium();
                            // Fragile way to detect a place holder image returned from Deezer:
                            // ex: "https://e-cdns-images.dzcdn.net/images/artist//250x250-000000-80-0-0.jpg"
                            // the double slash implies no artist identified
                            final boolean placeholderUrl = url.contains("/images/artist//");
                            if (!placeholderUrl) {
                                streamFetcher = new OkHttpStreamFetcher(okhttp, new GlideUrl(url));
                                streamFetcher.loadData(priority, callback);
                            }
                        }
                    } catch (Exception e) {
                        callback.onLoadFailed(e);
                    }
                }

                @Override
                public void onFailure(@NonNull Call<DeezerResponse> call, @NonNull Throwable throwable) {
                    callback.onLoadFailed(new Exception(throwable));
                }
            });
        }
    } catch (Exception e) {
        callback.onLoadFailed(e);
    }
}

18 Source : StickerRemoteUriFetcher.java
with GNU General Public License v3.0
from mollyim

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
    try {
        byte[] packIdBytes = Hex.fromStringCondensed(stickerUri.getPackId());
        byte[] packKeyBytes = Hex.fromStringCondensed(stickerUri.getPackKey());
        InputStream stream = receiver.retrieveSticker(packIdBytes, packKeyBytes, stickerUri.getStickerId());
        callback.onDataReady(stream);
    } catch (IOException | InvalidMessageException e) {
        callback.onLoadFailed(e);
    }
}

18 Source : ChunkedImageUrlFetcher.java
with GNU General Public License v3.0
from mollyim

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
    ChunkedDataFetcher fetcher = new ChunkedDataFetcher(client);
    requestController = fetcher.fetch(url.getUrl(), url.getSize(), new ChunkedDataFetcher.Callback() {

        @Override
        public void onSuccess(InputStream stream) {
            callback.onDataReady(stream);
        }

        @Override
        public void onFailure(Exception e) {
            callback.onLoadFailed(e);
        }
    });
}

18 Source : ArtistImageFetcher.java
with GNU General Public License v3.0
from MaxFour

@Override
public InputStream loadData(Priority priority) throws Exception {
    Log.d("MOSAIC", "load data for" + model.artistName);
    return stream = getMosaic(model.albumCovers);
}

18 Source : DecodeJob.java
with Apache License 2.0
from guolindev

/**
 * A clreplaced responsible for decoding resources either from cached data or from the original source and applying
 * transformations and transcodes.
 *
 * @param <A> The type of the source data the resource can be decoded from.
 * @param <T> The type of resource that will be decoded.
 * @param <Z> The type of resource that will be transcoded from the decoded and transformed resource.
 */
clreplaced DecodeJob<A, T, Z> {

    private static final String TAG = "DecodeJob";

    private static final FileOpener DEFAULT_FILE_OPENER = new FileOpener();

    private final EngineKey resultKey;

    private final int width;

    private final int height;

    private final DataFetcher<A> fetcher;

    private final DataLoadProvider<A, T> loadProvider;

    private final Transformation<T> transformation;

    private final ResourceTranscoder<T, Z> transcoder;

    private final DiskCacheProvider diskCacheProvider;

    private final DiskCacheStrategy diskCacheStrategy;

    private final Priority priority;

    private final FileOpener fileOpener;

    private volatile boolean isCancelled;

    public DecodeJob(EngineKey resultKey, int width, int height, DataFetcher<A> fetcher, DataLoadProvider<A, T> loadProvider, Transformation<T> transformation, ResourceTranscoder<T, Z> transcoder, DiskCacheProvider diskCacheProvider, DiskCacheStrategy diskCacheStrategy, Priority priority) {
        this(resultKey, width, height, fetcher, loadProvider, transformation, transcoder, diskCacheProvider, diskCacheStrategy, priority, DEFAULT_FILE_OPENER);
    }

    // Visible for testing.
    DecodeJob(EngineKey resultKey, int width, int height, DataFetcher<A> fetcher, DataLoadProvider<A, T> loadProvider, Transformation<T> transformation, ResourceTranscoder<T, Z> transcoder, DiskCacheProvider diskCacheProvider, DiskCacheStrategy diskCacheStrategy, Priority priority, FileOpener fileOpener) {
        this.resultKey = resultKey;
        this.width = width;
        this.height = height;
        this.fetcher = fetcher;
        this.loadProvider = loadProvider;
        this.transformation = transformation;
        this.transcoder = transcoder;
        this.diskCacheProvider = diskCacheProvider;
        this.diskCacheStrategy = diskCacheStrategy;
        this.priority = priority;
        this.fileOpener = fileOpener;
    }

    /**
     * Returns a transcoded resource decoded from transformed resource data in the disk cache, or null if no such
     * resource exists.
     *
     * @throws Exception
     */
    public Resource<Z> decodeResultFromCache() throws Exception {
        if (!diskCacheStrategy.cacheResult()) {
            return null;
        }
        long startTime = LogTime.getLogTime();
        Resource<T> transformed = loadFromCache(resultKey);
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logWithTimeAndKey("Decoded transformed from cache", startTime);
        }
        startTime = LogTime.getLogTime();
        Resource<Z> result = transcode(transformed);
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logWithTimeAndKey("Transcoded transformed from cache", startTime);
        }
        return result;
    }

    /**
     * Returns a transformed and transcoded resource decoded from source data in the disk cache, or null if no such
     * resource exists.
     *
     * @throws Exception
     */
    public Resource<Z> decodeSourceFromCache() throws Exception {
        if (!diskCacheStrategy.cacheSource()) {
            return null;
        }
        long startTime = LogTime.getLogTime();
        Resource<T> decoded = loadFromCache(resultKey.getOriginalKey());
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logWithTimeAndKey("Decoded source from cache", startTime);
        }
        return transformEncodeAndTranscode(decoded);
    }

    /**
     * Returns a transformed and transcoded resource decoded from source data, or null if no source data could be
     * obtained or no resource could be decoded.
     *
     * <p>
     *     Depending on the {@link DiskCacheStrategy} used, source data is either decoded
     *     directly or first written to the disk cache and then decoded from the disk cache.
     * </p>
     *
     * @throws Exception
     */
    public Resource<Z> decodeFromSource() throws Exception {
        Resource<T> decoded = decodeSource();
        return transformEncodeAndTranscode(decoded);
    }

    public void cancel() {
        isCancelled = true;
        fetcher.cancel();
    }

    private Resource<Z> transformEncodeAndTranscode(Resource<T> decoded) {
        long startTime = LogTime.getLogTime();
        Resource<T> transformed = transform(decoded);
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logWithTimeAndKey("Transformed resource from source", startTime);
        }
        writeTransformedToCache(transformed);
        startTime = LogTime.getLogTime();
        Resource<Z> result = transcode(transformed);
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logWithTimeAndKey("Transcoded transformed from source", startTime);
        }
        return result;
    }

    private void writeTransformedToCache(Resource<T> transformed) {
        if (transformed == null || !diskCacheStrategy.cacheResult()) {
            return;
        }
        long startTime = LogTime.getLogTime();
        SourceWriter<Resource<T>> writer = new SourceWriter<Resource<T>>(loadProvider.getEncoder(), transformed);
        diskCacheProvider.getDiskCache().put(resultKey, writer);
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logWithTimeAndKey("Wrote transformed from source to cache", startTime);
        }
    }

    private Resource<T> decodeSource() throws Exception {
        Resource<T> decoded = null;
        try {
            long startTime = LogTime.getLogTime();
            final A data = fetcher.loadData(priority);
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                logWithTimeAndKey("Fetched data", startTime);
            }
            if (isCancelled) {
                return null;
            }
            decoded = decodeFromSourceData(data);
        } finally {
            fetcher.cleanup();
        }
        return decoded;
    }

    private Resource<T> decodeFromSourceData(A data) throws IOException {
        final Resource<T> decoded;
        if (diskCacheStrategy.cacheSource()) {
            decoded = cacheAndDecodeSourceData(data);
        } else {
            long startTime = LogTime.getLogTime();
            decoded = loadProvider.getSourceDecoder().decode(data, width, height);
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                logWithTimeAndKey("Decoded from source", startTime);
            }
        }
        return decoded;
    }

    private Resource<T> cacheAndDecodeSourceData(A data) throws IOException {
        long startTime = LogTime.getLogTime();
        SourceWriter<A> writer = new SourceWriter<A>(loadProvider.getSourceEncoder(), data);
        diskCacheProvider.getDiskCache().put(resultKey.getOriginalKey(), writer);
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logWithTimeAndKey("Wrote source to cache", startTime);
        }
        startTime = LogTime.getLogTime();
        Resource<T> result = loadFromCache(resultKey.getOriginalKey());
        if (Log.isLoggable(TAG, Log.VERBOSE) && result != null) {
            logWithTimeAndKey("Decoded source from cache", startTime);
        }
        return result;
    }

    private Resource<T> loadFromCache(Key key) throws IOException {
        File cacheFile = diskCacheProvider.getDiskCache().get(key);
        if (cacheFile == null) {
            return null;
        }
        Resource<T> result = null;
        try {
            result = loadProvider.getCacheDecoder().decode(cacheFile, width, height);
        } finally {
            if (result == null) {
                diskCacheProvider.getDiskCache().delete(key);
            }
        }
        return result;
    }

    private Resource<T> transform(Resource<T> decoded) {
        if (decoded == null) {
            return null;
        }
        Resource<T> transformed = transformation.transform(decoded, width, height);
        if (!decoded.equals(transformed)) {
            decoded.recycle();
        }
        return transformed;
    }

    private Resource<Z> transcode(Resource<T> transformed) {
        if (transformed == null) {
            return null;
        }
        return transcoder.transcode(transformed);
    }

    private void logWithTimeAndKey(String message, long startTime) {
        Log.v(TAG, message + " in " + LogTime.getElapsedMillis(startTime) + ", key: " + resultKey);
    }

    clreplaced SourceWriter<DataType> implements DiskCache.Writer {

        private final Encoder<DataType> encoder;

        private final DataType data;

        public SourceWriter(Encoder<DataType> encoder, DataType data) {
            this.encoder = encoder;
            this.data = data;
        }

        @Override
        public boolean write(File file) {
            boolean success = false;
            OutputStream os = null;
            try {
                os = fileOpener.open(file);
                success = encoder.encode(data, os);
            } catch (FileNotFoundException e) {
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "Failed to find file to write to disk cache", e);
                }
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                    // Do nothing.
                    }
                }
            }
            return success;
        }
    }

    interface DiskCacheProvider {

        DiskCache getDiskCache();
    }

    static clreplaced FileOpener {

        public OutputStream open(File file) throws FileNotFoundException {
            return new BufferedOutputStream(new FileOutputStream(file));
        }
    }
}

17 Source : OkHttpStreamFetcher.java
with Apache License 2.0
from yinlingchaoliu

@Override
public InputStream loadData(Priority priority) throws Exception {
    Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());
    for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
        String key = headerEntry.getKey();
        requestBuilder.addHeader(key, headerEntry.getValue());
    }
    Request request = requestBuilder.build();
    Response response = client.newCall(request).execute();
    responseBody = response.body();
    if (!response.isSuccessful()) {
        throw new IOException("Request failed with code: " + response.code());
    }
    long contentLength = responseBody.contentLength();
    stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
    return stream;
}

17 Source : OkHttpStreamFetcher.java
with Apache License 2.0
from xiaobailong24

@Override
public void loadData(Priority priority, final DataCallback<? super InputStream> callback) {
    Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());
    for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
        String key = headerEntry.getKey();
        requestBuilder.addHeader(key, headerEntry.getValue());
    }
    Request request = requestBuilder.build();
    call = client.newCall(request);
    call.enqueue(new okhttp3.Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "OkHttp failed to obtain result", e);
            }
            callback.onLoadFailed(e);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            responseBody = response.body();
            if (response.isSuccessful()) {
                long contentLength = responseBody.contentLength();
                stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
                callback.onDataReady(stream);
            } else {
                callback.onLoadFailed(new HttpException(response.message(), response.code()));
            }
        }
    });
}

17 Source : OkHttpStreamFetcher.java
with GNU General Public License v3.0
from XecureIT

@Override
public void loadData(Priority priority, DataCallback<? super InputStream> callback) {
    try {
        Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());
        for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
            String key = headerEntry.getKey();
            requestBuilder.addHeader(key, headerEntry.getValue());
        }
        Request request = requestBuilder.build();
        Response response = client.newCall(request).execute();
        responseBody = response.body();
        if (!response.isSuccessful()) {
            throw new IOException("Request failed with code: " + response.code());
        }
        long contentLength = responseBody.contentLength();
        stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
        callback.onDataReady(stream);
    } catch (IOException e) {
        callback.onLoadFailed(e);
    }
}

17 Source : MultiFetcher.java
with GNU General Public License v3.0
from timusus

@Override
public InputStream loadData(Priority priority) throws Exception {
    InputStream inputStream = null;
    // Custom/user selected artwork. Loads from a specific source.
    UserSelectedArtwork userSelectedArtwork = ((ShuttleApplication) applicationContext).userSelectedArtwork.get(artworkProvider.getArtworkKey());
    if (userSelectedArtwork != null) {
        switch(userSelectedArtwork.type) {
            case ArtworkProvider.Type.MEDIA_STORE:
                dataFetcher = new MediaStoreFetcher(applicationContext, artworkProvider);
                break;
            case ArtworkProvider.Type.FOLDER:
                dataFetcher = new FolderFetcher(artworkProvider, new File(userSelectedArtwork.path));
                break;
            case ArtworkProvider.Type.TAG:
                dataFetcher = new TagFetcher(artworkProvider);
                break;
            case ArtworkProvider.Type.REMOTE:
                dataFetcher = new RemoteFetcher(artworkProvider);
                break;
        }
        inputStream = loadData(dataFetcher, priority);
    }
    // No user selected artwork. Check local then remote sources, according to user's preferences.
    // Check the MediaStore
    if (inputStream == null && !settingsManager.ignoreMediaStoreArtwork()) {
        dataFetcher = new MediaStoreFetcher(applicationContext, artworkProvider);
        inputStream = loadData(dataFetcher, priority);
    }
    if (inputStream == null) {
        if (settingsManager.preferEmbeddedArtwork()) {
            // Check tags
            if (!settingsManager.ignoreEmbeddedArtwork()) {
                dataFetcher = new TagFetcher(artworkProvider);
                inputStream = loadData(dataFetcher, priority);
            }
            // Check folders
            if (inputStream == null && !settingsManager.ignoreFolderArtwork()) {
                dataFetcher = new FolderFetcher(artworkProvider, null);
                inputStream = loadData(dataFetcher, priority);
            }
        } else {
            // Check folders
            if (!settingsManager.ignoreFolderArtwork()) {
                dataFetcher = new FolderFetcher(artworkProvider, null);
                inputStream = loadData(dataFetcher, priority);
            }
            // Check tags
            if (inputStream == null && !settingsManager.ignoreEmbeddedArtwork()) {
                dataFetcher = new TagFetcher(artworkProvider);
                inputStream = loadData(dataFetcher, priority);
            }
        }
    }
    if (inputStream == null) {
        if (allowOfflineDownload || (settingsManager.canDownloadArtworkAutomatically() && ShuttleUtils.isOnline(applicationContext, true))) {
            // Last FM
            dataFetcher = new RemoteFetcher(artworkProvider);
            inputStream = loadData(dataFetcher, priority);
        }
    }
    return inputStream;
}

17 Source : OkHttpStreamFetcher.java
with MIT License
from qunarcorp

@Override
public InputStream loadData(Priority priority) throws Exception {
    Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());
    for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
        String key = headerEntry.getKey();
        requestBuilder.addHeader(key, headerEntry.getValue());
    }
    Request request = requestBuilder.build();
    Response response;
    call = client.newCall(request);
    response = call.execute();
    responseBody = response.body();
    if (!response.isSuccessful()) {
        throw new IOException("Request failed with code: " + response.code());
    }
    long contentLength = responseBody.contentLength();
    stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
    return stream;
}

17 Source : OkHttpStreamFetcher.java
with Apache License 2.0
from nicolite

@Override
public InputStream loadData(Priority priority) throws Exception {
    Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());
    for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
        String key = headerEntry.getKey();
        requestBuilder.addHeader(key, headerEntry.getValue());
    }
    Request request = requestBuilder.build();
    Response response;
    call = client.newCall(request);
    response = call.execute();
    responseBody = response.body();
    if (!response.isSuccessful()) {
        throw new IOException("Request failed with code: " + response.code());
    }
    long contentLength = responseBody.contentLength();
    stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength, url.toStringUrl());
    return stream;
}

17 Source : OkHttpStreamFetcher.java
with GNU General Public License v3.0
from mollyim

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
    try {
        Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());
        for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
            String key = headerEntry.getKey();
            requestBuilder.addHeader(key, headerEntry.getValue());
        }
        Request request = requestBuilder.build();
        Response response = client.newCall(request).execute();
        responseBody = response.body();
        if (!response.isSuccessful()) {
            throw new IOException("Request failed with code: " + response.code());
        }
        long contentLength = responseBody.contentLength();
        stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
        callback.onDataReady(stream);
    } catch (IOException e) {
        callback.onLoadFailed(e);
    }
}

17 Source : ProgressDataFetcher.java
with Apache License 2.0
from liying2008

@Override
public InputStream loadData(Priority priority) throws Exception {
    if (isUrl) {
        Request request = new Request.Builder().url(url).build();
        final ProgressListener glideProgressListener = new ProgressListener() {

            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                // Log.e(TAG, bytesRead + "," + contentLength + done);
                if (handler != null) {
                    Message message = handler.obtainMessage();
                    message.what = 1;
                    message.arg1 = (int) bytesRead;
                    message.arg2 = (int) contentLength;
                    handler.sendMessage(message);
                }
            }
        };
        OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder().body(new ProgressResponseBody(originalResponse.body(), glideProgressListener)).build();
            }
        }).build();
        try {
            progressCall = client.newCall(request);
            Response response = progressCall.execute();
            if (isCancelled) {
                return null;
            }
            if (!response.isSuccessful())
                throw new IOException("Unexpected code " + response);
            stream = response.body().byteStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stream;
    } else {
        return new FileInputStream(url);
    }
}

17 Source : OkHttpStreamFetcher.java
with Apache License 2.0
from HelloChenJinJun

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
    Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());
    for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
        String key = headerEntry.getKey();
        requestBuilder.addHeader(key, headerEntry.getValue());
    }
    Request request = requestBuilder.build();
    Response response = null;
    call = client.newCall(request);
    try {
        response = call.execute();
        responseBody = response.body();
    } catch (IOException e) {
        e.printStackTrace();
        callback.onLoadFailed(new IOException("Request failed with code: "));
        return;
    }
    long contentLength = responseBody.contentLength();
    stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
    callback.onDataReady(stream);
}

17 Source : GenericRequest.java
with Apache License 2.0
from guolindev

/**
 * A {@link Request} that loads a {@link Resource} into a given {@link Target}.
 *
 * @param <A> The type of the model that the resource will be loaded from.
 * @param <T> The type of the data that the resource will be loaded from.
 * @param <Z> The type of the resource that will be loaded.
 * @param <R> The type of the resource that will be transcoded from the loaded resource.
 */
public final clreplaced GenericRequest<A, T, Z, R> implements Request, SizeReadyCallback, ResourceCallback {

    private static final String TAG = "GenericRequest";

    private static final Queue<GenericRequest<?, ?, ?, ?>> REQUEST_POOL = Util.createQueue(0);

    private static final double TO_MEGABYTE = 1d / (1024d * 1024d);

    private enum Status {

        /**
         * Created but not yet running.
         */
        PENDING,
        /**
         * In the process of fetching media.
         */
        RUNNING,
        /**
         * Waiting for a callback given to the Target to be called to determine target dimensions.
         */
        WAITING_FOR_SIZE,
        /**
         * Finished loading media successfully.
         */
        COMPLETE,
        /**
         * Failed to load media, may be restarted.
         */
        FAILED,
        /**
         * Cancelled by the user, may not be restarted.
         */
        CANCELLED,
        /**
         * Cleared by the user with a placeholder set, may not be restarted.
         */
        CLEARED,
        /**
         * Temporarily paused by the system, may be restarted.
         */
        PAUSED
    }

    private final String tag = String.valueOf(hashCode());

    private Key signature;

    private Drawable fallbackDrawable;

    private int fallbackResourceId;

    private int placeholderResourceId;

    private int errorResourceId;

    private Context context;

    private Transformation<Z> transformation;

    private LoadProvider<A, T, Z, R> loadProvider;

    private RequestCoordinator requestCoordinator;

    private A model;

    private Clreplaced<R> transcodeClreplaced;

    private boolean isMemoryCacheable;

    private Priority priority;

    private Target<R> target;

    private RequestListener<? super A, R> requestListener;

    private float sizeMultiplier;

    private Engine engine;

    private GlideAnimationFactory<R> animationFactory;

    private int overrideWidth;

    private int overrideHeight;

    private DiskCacheStrategy diskCacheStrategy;

    private Drawable placeholderDrawable;

    private Drawable errorDrawable;

    private boolean loadedFromMemoryCache;

    // doing our own type check
    private Resource<?> resource;

    private Engine.LoadStatus loadStatus;

    private long startTime;

    private Status status;

    public static <A, T, Z, R> GenericRequest<A, T, Z, R> obtain(LoadProvider<A, T, Z, R> loadProvider, A model, Key signature, Context context, Priority priority, Target<R> target, float sizeMultiplier, Drawable placeholderDrawable, int placeholderResourceId, Drawable errorDrawable, int errorResourceId, Drawable fallbackDrawable, int fallbackResourceId, RequestListener<? super A, R> requestListener, RequestCoordinator requestCoordinator, Engine engine, Transformation<Z> transformation, Clreplaced<R> transcodeClreplaced, boolean isMemoryCacheable, GlideAnimationFactory<R> animationFactory, int overrideWidth, int overrideHeight, DiskCacheStrategy diskCacheStrategy) {
        @SuppressWarnings("unchecked")
        GenericRequest<A, T, Z, R> request = (GenericRequest<A, T, Z, R>) REQUEST_POOL.poll();
        if (request == null) {
            request = new GenericRequest<A, T, Z, R>();
        }
        request.init(loadProvider, model, signature, context, priority, target, sizeMultiplier, placeholderDrawable, placeholderResourceId, errorDrawable, errorResourceId, fallbackDrawable, fallbackResourceId, requestListener, requestCoordinator, engine, transformation, transcodeClreplaced, isMemoryCacheable, animationFactory, overrideWidth, overrideHeight, diskCacheStrategy);
        return request;
    }

    private GenericRequest() {
    // just create, instances are reused with recycle/init
    }

    @Override
    public void recycle() {
        loadProvider = null;
        model = null;
        context = null;
        target = null;
        placeholderDrawable = null;
        errorDrawable = null;
        fallbackDrawable = null;
        requestListener = null;
        requestCoordinator = null;
        transformation = null;
        animationFactory = null;
        loadedFromMemoryCache = false;
        loadStatus = null;
        REQUEST_POOL.offer(this);
    }

    private void init(LoadProvider<A, T, Z, R> loadProvider, A model, Key signature, Context context, Priority priority, Target<R> target, float sizeMultiplier, Drawable placeholderDrawable, int placeholderResourceId, Drawable errorDrawable, int errorResourceId, Drawable fallbackDrawable, int fallbackResourceId, RequestListener<? super A, R> requestListener, RequestCoordinator requestCoordinator, Engine engine, Transformation<Z> transformation, Clreplaced<R> transcodeClreplaced, boolean isMemoryCacheable, GlideAnimationFactory<R> animationFactory, int overrideWidth, int overrideHeight, DiskCacheStrategy diskCacheStrategy) {
        this.loadProvider = loadProvider;
        this.model = model;
        this.signature = signature;
        this.fallbackDrawable = fallbackDrawable;
        this.fallbackResourceId = fallbackResourceId;
        this.context = context.getApplicationContext();
        this.priority = priority;
        this.target = target;
        this.sizeMultiplier = sizeMultiplier;
        this.placeholderDrawable = placeholderDrawable;
        this.placeholderResourceId = placeholderResourceId;
        this.errorDrawable = errorDrawable;
        this.errorResourceId = errorResourceId;
        this.requestListener = requestListener;
        this.requestCoordinator = requestCoordinator;
        this.engine = engine;
        this.transformation = transformation;
        this.transcodeClreplaced = transcodeClreplaced;
        this.isMemoryCacheable = isMemoryCacheable;
        this.animationFactory = animationFactory;
        this.overrideWidth = overrideWidth;
        this.overrideHeight = overrideHeight;
        this.diskCacheStrategy = diskCacheStrategy;
        status = Status.PENDING;
        // We allow null models by just setting an error drawable. Null models will always have empty providers, we
        // simply skip our sanity checks in that unusual case.
        if (model != null) {
            check("ModelLoader", loadProvider.getModelLoader(), "try .using(ModelLoader)");
            check("Transcoder", loadProvider.getTranscoder(), "try .as*(Clreplaced).transcode(ResourceTranscoder)");
            check("Transformation", transformation, "try .transform(UnitTransformation.get())");
            if (diskCacheStrategy.cacheSource()) {
                check("SourceEncoder", loadProvider.getSourceEncoder(), "try .sourceEncoder(Encoder) or .diskCacheStrategy(NONE/RESULT)");
            } else {
                check("SourceDecoder", loadProvider.getSourceDecoder(), "try .decoder/.imageDecoder/.videoDecoder(ResourceDecoder) or .diskCacheStrategy(ALL/SOURCE)");
            }
            if (diskCacheStrategy.cacheSource() || diskCacheStrategy.cacheResult()) {
                // TODO if(resourceClreplaced.isreplacedignableFrom(InputStream.clreplaced) it is possible to wrap sourceDecoder
                // and use it instead of cacheDecoder: new FileToStreamDecoder<Z>(sourceDecoder)
                // in that case this shouldn't throw
                check("CacheDecoder", loadProvider.getCacheDecoder(), "try .cacheDecoder(ResouceDecoder) or .diskCacheStrategy(NONE)");
            }
            if (diskCacheStrategy.cacheResult()) {
                check("Encoder", loadProvider.getEncoder(), "try .encode(ResourceEncoder) or .diskCacheStrategy(NONE/SOURCE)");
            }
        }
    }

    private static void check(String name, Object object, String suggestion) {
        if (object == null) {
            StringBuilder message = new StringBuilder(name);
            message.append(" must not be null");
            if (suggestion != null) {
                message.append(", ");
                message.append(suggestion);
            }
            throw new NullPointerException(message.toString());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void begin() {
        startTime = LogTime.getLogTime();
        if (model == null) {
            onException(null);
            return;
        }
        status = Status.WAITING_FOR_SIZE;
        if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
            onSizeReady(overrideWidth, overrideHeight);
        } else {
            target.getSize(this);
        }
        if (!isComplete() && !isFailed() && canNotifyStatusChanged()) {
            target.onLoadStarted(getPlaceholderDrawable());
        }
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logV("finished run method in " + LogTime.getElapsedMillis(startTime));
        }
    }

    /**
     * Cancels the current load but does not release any resources held by the request and continues to display
     * the loaded resource if the load completed before the call to cancel.
     *
     * <p>
     *     Cancelled requests can be restarted with a subsequent call to {@link #begin()}.
     * </p>
     *
     * @see #clear()
     */
    void cancel() {
        status = Status.CANCELLED;
        if (loadStatus != null) {
            loadStatus.cancel();
            loadStatus = null;
        }
    }

    /**
     * Cancels the current load if it is in progress, clears any resources held onto by the request and replaces
     * the loaded resource if the load completed with the placeholder.
     *
     * <p>
     *     Cleared requests can be restarted with a subsequent call to {@link #begin()}
     * </p>
     *
     * @see #cancel()
     */
    @Override
    public void clear() {
        Util.replacedertMainThread();
        if (status == Status.CLEARED) {
            return;
        }
        cancel();
        // Resource must be released before canNotifyStatusChanged is called.
        if (resource != null) {
            releaseResource(resource);
        }
        if (canNotifyStatusChanged()) {
            target.onLoadCleared(getPlaceholderDrawable());
        }
        // Must be after cancel().
        status = Status.CLEARED;
    }

    @Override
    public boolean isPaused() {
        return status == Status.PAUSED;
    }

    @Override
    public void pause() {
        clear();
        status = Status.PAUSED;
    }

    private void releaseResource(Resource resource) {
        engine.release(resource);
        this.resource = null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isRunning() {
        return status == Status.RUNNING || status == Status.WAITING_FOR_SIZE;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isComplete() {
        return status == Status.COMPLETE;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isResourceSet() {
        return isComplete();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isCancelled() {
        return status == Status.CANCELLED || status == Status.CLEARED;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isFailed() {
        return status == Status.FAILED;
    }

    private Drawable getFallbackDrawable() {
        if (fallbackDrawable == null && fallbackResourceId > 0) {
            fallbackDrawable = context.getResources().getDrawable(fallbackResourceId);
        }
        return fallbackDrawable;
    }

    private void setErrorPlaceholder(Exception e) {
        if (!canNotifyStatusChanged()) {
            return;
        }
        Drawable error = model == null ? getFallbackDrawable() : null;
        if (error == null) {
            error = getErrorDrawable();
        }
        if (error == null) {
            error = getPlaceholderDrawable();
        }
        target.onLoadFailed(e, error);
    }

    private Drawable getErrorDrawable() {
        if (errorDrawable == null && errorResourceId > 0) {
            errorDrawable = context.getResources().getDrawable(errorResourceId);
        }
        return errorDrawable;
    }

    private Drawable getPlaceholderDrawable() {
        if (placeholderDrawable == null && placeholderResourceId > 0) {
            placeholderDrawable = context.getResources().getDrawable(placeholderResourceId);
        }
        return placeholderDrawable;
    }

    /**
     * A callback method that should never be invoked directly.
     */
    @Override
    public void onSizeReady(int width, int height) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logV("Got onSizeReady in " + LogTime.getElapsedMillis(startTime));
        }
        if (status != Status.WAITING_FOR_SIZE) {
            return;
        }
        status = Status.RUNNING;
        width = Math.round(sizeMultiplier * width);
        height = Math.round(sizeMultiplier * height);
        ModelLoader<A, T> modelLoader = loadProvider.getModelLoader();
        final DataFetcher<T> dataFetcher = modelLoader.getResourceFetcher(model, width, height);
        if (dataFetcher == null) {
            onException(new Exception("Failed to load model: \'" + model + "\'"));
            return;
        }
        ResourceTranscoder<Z, R> transcoder = loadProvider.getTranscoder();
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logV("finished setup for calling load in " + LogTime.getElapsedMillis(startTime));
        }
        loadedFromMemoryCache = true;
        loadStatus = engine.load(signature, width, height, dataFetcher, loadProvider, transformation, transcoder, priority, isMemoryCacheable, diskCacheStrategy, this);
        loadedFromMemoryCache = resource != null;
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logV("finished onSizeReady in " + LogTime.getElapsedMillis(startTime));
        }
    }

    private boolean canSetResource() {
        return requestCoordinator == null || requestCoordinator.canSetImage(this);
    }

    private boolean canNotifyStatusChanged() {
        return requestCoordinator == null || requestCoordinator.canNotifyStatusChanged(this);
    }

    private boolean isFirstReadyResource() {
        return requestCoordinator == null || !requestCoordinator.isAnyResourceSet();
    }

    private void notifyLoadSuccess() {
        if (requestCoordinator != null) {
            requestCoordinator.onRequestSuccess(this);
        }
    }

    /**
     * A callback method that should never be invoked directly.
     */
    @SuppressWarnings("unchecked")
    @Override
    public void onResourceReady(Resource<?> resource) {
        if (resource == null) {
            onException(new Exception("Expected to receive a Resource<R> with an object of " + transcodeClreplaced + " inside, but instead got null."));
            return;
        }
        Object received = resource.get();
        if (received == null || !transcodeClreplaced.isreplacedignableFrom(received.getClreplaced())) {
            releaseResource(resource);
            onException(new Exception("Expected to receive an object of " + transcodeClreplaced + " but instead got " + (received != null ? received.getClreplaced() : "") + "{" + received + "}" + " inside Resource{" + resource + "}." + (received != null ? "" : " " + "To indicate failure return a null Resource object, " + "rather than a Resource object containing null data.")));
            return;
        }
        if (!canSetResource()) {
            releaseResource(resource);
            // We can't set the status to complete before asking canSetResource().
            status = Status.COMPLETE;
            return;
        }
        onResourceReady(resource, (R) received);
    }

    /**
     * Internal {@link #onResourceReady(Resource)} where arguments are known to be safe.
     *
     * @param resource original {@link Resource}, never <code>null</code>
     * @param result object returned by {@link Resource#get()}, checked for type and never <code>null</code>
     */
    private void onResourceReady(Resource<?> resource, R result) {
        // We must call isFirstReadyResource before setting status.
        boolean isFirstResource = isFirstReadyResource();
        status = Status.COMPLETE;
        this.resource = resource;
        if (requestListener == null || !requestListener.onResourceReady(result, model, target, loadedFromMemoryCache, isFirstResource)) {
            GlideAnimation<R> animation = animationFactory.build(loadedFromMemoryCache, isFirstResource);
            target.onResourceReady(result, animation);
        }
        notifyLoadSuccess();
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            logV("Resource ready in " + LogTime.getElapsedMillis(startTime) + " size: " + (resource.getSize() * TO_MEGABYTE) + " fromCache: " + loadedFromMemoryCache);
        }
    }

    /**
     * A callback method that should never be invoked directly.
     */
    @Override
    public void onException(Exception e) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "load failed", e);
        }
        status = Status.FAILED;
        // TODO: what if this is a thumbnail request?
        if (requestListener == null || !requestListener.onException(e, model, target, isFirstReadyResource())) {
            setErrorPlaceholder(e);
        }
    }

    private void logV(String message) {
        Log.v(TAG, message + " this: " + tag);
    }
}

17 Source : GenericRequest.java
with Apache License 2.0
from guolindev

public static <A, T, Z, R> GenericRequest<A, T, Z, R> obtain(LoadProvider<A, T, Z, R> loadProvider, A model, Key signature, Context context, Priority priority, Target<R> target, float sizeMultiplier, Drawable placeholderDrawable, int placeholderResourceId, Drawable errorDrawable, int errorResourceId, Drawable fallbackDrawable, int fallbackResourceId, RequestListener<? super A, R> requestListener, RequestCoordinator requestCoordinator, Engine engine, Transformation<Z> transformation, Clreplaced<R> transcodeClreplaced, boolean isMemoryCacheable, GlideAnimationFactory<R> animationFactory, int overrideWidth, int overrideHeight, DiskCacheStrategy diskCacheStrategy) {
    @SuppressWarnings("unchecked")
    GenericRequest<A, T, Z, R> request = (GenericRequest<A, T, Z, R>) REQUEST_POOL.poll();
    if (request == null) {
        request = new GenericRequest<A, T, Z, R>();
    }
    request.init(loadProvider, model, signature, context, priority, target, sizeMultiplier, placeholderDrawable, placeholderResourceId, errorDrawable, errorResourceId, fallbackDrawable, fallbackResourceId, requestListener, requestCoordinator, engine, transformation, transcodeClreplaced, isMemoryCacheable, animationFactory, overrideWidth, overrideHeight, diskCacheStrategy);
    return request;
}

17 Source : HttpUrlFetcher.java
with Apache License 2.0
from guolindev

@Override
public InputStream loadData(Priority priority) throws Exception {
    return loadDataWithRedirects(glideUrl.toURL(), 0, /*redirects*/
    null, /*lastUrl*/
    glideUrl.getHeaders());
}

17 Source : ArtistImageFetcher.java
with GNU General Public License v3.0
from deepshooter

@Override
public InputStream loadData(Priority priority) throws Exception {
    if (!MusicUtil.isArtistNameUnknown(model.artistName) && Util.isAllowedToDownloadMetadata(context)) {
        Response<LastFmArtist> response = lastFMRestClient.getApiService().getArtistInfo(model.artistName, null, model.skipOkHttpCache ? "no-cache" : null).execute();
        if (!response.isSuccessful()) {
            throw new IOException("Request failed with code: " + response.code());
        }
        LastFmArtist lastFmArtist = response.body();
        if (isCancelled)
            return null;
        GlideUrl url = new GlideUrl(LastFMUtil.getLargestArtistImageUrl(lastFmArtist.getArtist().getImage()));
        urlFetcher = urlLoader.getResourceFetcher(url, width, height);
        return urlFetcher.loadData(priority);
    }
    return null;
}

17 Source : AudioFileCoverFetcher.java
with GNU General Public License v3.0
from AdrienPoupa

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    InputStream data;
    try {
        retriever.setDataSource(model.filePath);
        byte[] picture = retriever.getEmbeddedPicture();
        if (picture != null) {
            data = new ByteArrayInputStream(picture);
        } else {
            data = fallback(model.filePath);
        }
        callback.onDataReady(data);
    } catch (FileNotFoundException e) {
        callback.onLoadFailed(e);
    } finally {
        retriever.release();
    }
}

16 Source : AudioCoverDataFetcher.java
with GNU General Public License v3.0
from rasheedsulayman

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
    if (TextUtils.isEmpty(audioCoverImage.filePath)) {
        callback.onDataReady(null);
        return;
    }
    // First try MediaMetadataRetriever
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    try {
        retriever.setDataSource(audioCoverImage.filePath);
        byte[] picture = retriever.getEmbeddedPicture();
        if (picture != null) {
            callback.onDataReady(new ByteArrayInputStream(picture));
        } else {
            callback.onDataReady(fallback(audioCoverImage.filePath));
        }
    } finally {
        retriever.release();
    }
}

16 Source : OkHttpStreamFetcher.java
with Apache License 2.0
from JessYanCoding

@Override
public void loadData(@NonNull Priority priority, @NonNull final DataCallback<? super InputStream> callback) {
    Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());
    for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
        String key = headerEntry.getKey();
        requestBuilder.addHeader(key, headerEntry.getValue());
    }
    Request request = requestBuilder.build();
    this.callback = callback;
    call = client.newCall(request);
    call.enqueue(this);
}

16 Source : GenericRequest.java
with Apache License 2.0
from guolindev

private void init(LoadProvider<A, T, Z, R> loadProvider, A model, Key signature, Context context, Priority priority, Target<R> target, float sizeMultiplier, Drawable placeholderDrawable, int placeholderResourceId, Drawable errorDrawable, int errorResourceId, Drawable fallbackDrawable, int fallbackResourceId, RequestListener<? super A, R> requestListener, RequestCoordinator requestCoordinator, Engine engine, Transformation<Z> transformation, Clreplaced<R> transcodeClreplaced, boolean isMemoryCacheable, GlideAnimationFactory<R> animationFactory, int overrideWidth, int overrideHeight, DiskCacheStrategy diskCacheStrategy) {
    this.loadProvider = loadProvider;
    this.model = model;
    this.signature = signature;
    this.fallbackDrawable = fallbackDrawable;
    this.fallbackResourceId = fallbackResourceId;
    this.context = context.getApplicationContext();
    this.priority = priority;
    this.target = target;
    this.sizeMultiplier = sizeMultiplier;
    this.placeholderDrawable = placeholderDrawable;
    this.placeholderResourceId = placeholderResourceId;
    this.errorDrawable = errorDrawable;
    this.errorResourceId = errorResourceId;
    this.requestListener = requestListener;
    this.requestCoordinator = requestCoordinator;
    this.engine = engine;
    this.transformation = transformation;
    this.transcodeClreplaced = transcodeClreplaced;
    this.isMemoryCacheable = isMemoryCacheable;
    this.animationFactory = animationFactory;
    this.overrideWidth = overrideWidth;
    this.overrideHeight = overrideHeight;
    this.diskCacheStrategy = diskCacheStrategy;
    status = Status.PENDING;
    // We allow null models by just setting an error drawable. Null models will always have empty providers, we
    // simply skip our sanity checks in that unusual case.
    if (model != null) {
        check("ModelLoader", loadProvider.getModelLoader(), "try .using(ModelLoader)");
        check("Transcoder", loadProvider.getTranscoder(), "try .as*(Clreplaced).transcode(ResourceTranscoder)");
        check("Transformation", transformation, "try .transform(UnitTransformation.get())");
        if (diskCacheStrategy.cacheSource()) {
            check("SourceEncoder", loadProvider.getSourceEncoder(), "try .sourceEncoder(Encoder) or .diskCacheStrategy(NONE/RESULT)");
        } else {
            check("SourceDecoder", loadProvider.getSourceDecoder(), "try .decoder/.imageDecoder/.videoDecoder(ResourceDecoder) or .diskCacheStrategy(ALL/SOURCE)");
        }
        if (diskCacheStrategy.cacheSource() || diskCacheStrategy.cacheResult()) {
            // TODO if(resourceClreplaced.isreplacedignableFrom(InputStream.clreplaced) it is possible to wrap sourceDecoder
            // and use it instead of cacheDecoder: new FileToStreamDecoder<Z>(sourceDecoder)
            // in that case this shouldn't throw
            check("CacheDecoder", loadProvider.getCacheDecoder(), "try .cacheDecoder(ResouceDecoder) or .diskCacheStrategy(NONE)");
        }
        if (diskCacheStrategy.cacheResult()) {
            check("Encoder", loadProvider.getEncoder(), "try .encode(ResourceEncoder) or .diskCacheStrategy(NONE/SOURCE)");
        }
    }
}

16 Source : OkHttpFetcher.java
with Apache License 2.0
from getActivity

@Override
public void loadData(@NonNull Priority priority, @NonNull final DataFetcher.DataCallback<? super InputStream> callback) {
    Request.Builder requestBuilder = new Request.Builder().url(mGlideUrl.toStringUrl());
    for (Map.Entry<String, String> headerEntry : mGlideUrl.getHeaders().entrySet()) {
        String key = headerEntry.getKey();
        requestBuilder.addHeader(key, headerEntry.getValue());
    }
    Request request = requestBuilder.build();
    mDataCallback = callback;
    mCall = mCallFactory.newCall(request);
    mCall.enqueue(this);
}

15 Source : OkHttpStreamFetcher.java
with Apache License 2.0
from Zweihui

@Override
public void loadData(Priority priority, final DataCallback<? super InputStream> callback) {
    Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());
    for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
        String key = headerEntry.getKey();
        requestBuilder.addHeader(key, headerEntry.getValue());
    }
    Request request = requestBuilder.build();
    this.callback = callback;
    call = client.newCall(request);
    if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
        call.enqueue(this);
    } else {
        try {
            // Calling execute instead of enqueue is a workaround for #2355, where okhttp throws a
            // ClreplacedCastException on O.
            onResponse(call, call.execute());
        } catch (IOException e) {
            onFailure(call, e);
        } catch (ClreplacedCastException e) {
            // It's not clear that this catch is necessary, the error may only occur even on O if
            // enqueue is used.
            onFailure(call, new IOException("Workaround for framework bug on O", e));
        }
    }
}

15 Source : GiphyPaddedUrlFetcher.java
with GNU General Public License v3.0
from XecureIT

@Override
public void loadData(Priority priority, DataCallback<? super InputStream> callback) {
    bodies = new LinkedList<>();
    rangeStreams = new LinkedList<>();
    stream = null;
    try {
        List<ByteRange> requestPattern = getRequestPattern(url.getSize());
        for (ByteRange range : requestPattern) {
            Request request = new Request.Builder().addHeader("Range", "bytes=" + range.start + "-" + range.end).addHeader("Accept-Encoding", "idenreplacedy").url(url.getTarget()).get().build();
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new IOException("Bad response: " + response.code() + " - " + response.message());
            }
            ResponseBody responseBody = response.body();
            if (responseBody == null)
                throw new IOException("Response body was null");
            else
                bodies.add(responseBody);
            rangeStreams.add(new SkippingInputStream(ContentLengthInputStream.obtain(responseBody.byteStream(), responseBody.contentLength()), range.ignoreFirst));
        }
        stream = new InputStreamList(rangeStreams);
        callback.onDataReady(stream);
    } catch (IOException e) {
        Log.w(TAG, e);
        callback.onLoadFailed(e);
    }
}

15 Source : OkHttpStreamFetcher.java
with Apache License 2.0
from shengjunhu

@Override
public void loadData(Priority priority, final DataCallback<? super InputStream> callback) {
    Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());
    for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
        String key = headerEntry.getKey();
        requestBuilder.addHeader(key, headerEntry.getValue());
    }
    Request request = requestBuilder.build();
    this.callback = callback;
    call = client.newCall(request);
    // Build.VERSION.SDK_INT != Build.VERSION_CODES.O
    if (Build.VERSION.SDK_INT != 26) {
        call.enqueue(this);
    } else {
        try {
            // Calling execute instead of enqueue is a workaround for #2355, where okhttp throws a
            // ClreplacedCastException on O.
            onResponse(call, call.execute());
        } catch (IOException e) {
            onFailure(call, e);
        } catch (ClreplacedCastException e) {
            // It's not clear that this catch is necessary, the error may only occur even on O if
            // enqueue is used.
            onFailure(call, new IOException("Workaround for framework bug on O", e));
        }
    }
}

15 Source : MddPicFetcher.java
with GNU General Public License v3.0
from KnIfER

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
    String err = null;
    try {
        ByteArrayInputStream resTmp = null;
        for (mdictRes mddTmp : model.mdd) {
            int idx = mddTmp.lookUp(model.path);
            if (idx != -1) {
                resTmp = mddTmp.getResourseAt(idx);
                if (resTmp != null)
                    break;
            }
        }
        if (resTmp != null) {
            if (model.path.endsWith(".tif") || model.path.endsWith(".tiff")) {
                BufferedImage image = Imaging.getBufferedImage(resTmp, getTifConfig());
                ByteArrayRandomOutputStream bos = new ByteArrayRandomOutputStream((int) (resTmp.available() * 2.5));
                image.bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                resTmp = new ByteArrayInputStream(bos.toByteArray());
            }
            callback.onDataReady(resTmp);
            return;
        }
    } catch (Exception e) {
        err = e.toString();
    }
    callback.onLoadFailed(new Exception("load mdd picture fail" + err));
}

See More Examples