@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; }
@Override public DataFetcher<InputStream> getResourceFetcher(final String model, int width, int height) { return new DataFetcher<InputStream>() { @Override public InputStream loadData(Priority priority) throws Exception { throw new IOException("Forced Glide network failure"); } @Override public void cleanup() { } @Override public String getId() { return model; } @Override public void cancel() { } }; }
@Override public void loadData(Priority priority, final DataCallback<? super InputStream> callback) { mStreamTask = mRef.getStream(); mStreamTask .addOnSuccessListener(new OnSuccessListener<StreamDownloadTask.TaskSnapshot>() { @Override public void onSuccess(StreamDownloadTask.TaskSnapshot snapshot) { mInputStream = snapshot.getStream(); callback.onDataReady(mInputStream); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { callback.onLoadFailed(e); } }); }
@Override public View instantiateItem(ViewGroup container, int position) { View view=inflater.inflate(R.layout.adapter_album,container,false); ImageView image= ButterKnife.findById(view,R.id.image); Glide.with(container.getContext()) .load(albums.get(position).getArtworkUrl()) .asBitmap() .priority(Priority.IMMEDIATE) .diskCacheStrategy(DiskCacheStrategy.RESULT) .into(new ImageViewTarget<Bitmap>(image) { @Override protected void setResource(Bitmap resource) { image.setImageBitmap(resource); if (position == current && !isLoaded) { isLoaded = true; if (callback != null) { callback.onTransitionImageLoaded(image,resource); } } } }); container.addView(view); return view; }
@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; }
@Override public void loadData(Priority priority, DataCallback<? super File> callback) { Cursor cursor = context.getContentResolver().query(uri, PROJECTION, null /*selection*/, null /*selectionArgs*/, null /*sortOrder*/); String filePath = null; if (cursor != null) { try { if (cursor.moveToFirst()) { filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)); } } finally { cursor.close(); } } if (TextUtils.isEmpty(filePath)) { callback.onLoadFailed(new FileNotFoundException("Failed to find file path for: " + uri)); } else { callback.onDataReady(new File(filePath)); } }
@Override public void loadData(Priority priority, DataCallback<? super InputStream> callback) { long startTime = LogTime.getLogTime(); final InputStream result; try { result = loadDataWithRedirects(glideUrl.toURL(), 0 /*redirects*/, null /*lastUrl*/, glideUrl.getHeaders()); } catch (IOException e) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Failed to load data for url", e); } callback.onLoadFailed(e); return; } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Finished http url fetcher fetch in " + LogTime.getElapsedMillis(startTime) + " ms and loaded " + result); } callback.onDataReady(result); }
@Test public void testCanReRunCancelledRequests() { doAnswer(new CallSizeReady(100, 100)).when(harness.target) .getSize(any(SizeReadyCallback.class)); when(harness.engine .load(eq(harness.glideContext), eq(harness.model), eq(harness.signature), eq(100), eq(100), eq(Object.class), eq(List.class), any(Priority.class), any(DiskCacheStrategy.class), eq(harness.transformations), anyBoolean(), any(Options.class), anyBoolean(), anyBoolean(), anyBoolean(), any(ResourceCallback.class))) .thenAnswer(new CallResourceCallback(harness.resource)); SingleRequest<List> request = harness.getRequest(); request.begin(); request.cancel(); request.begin(); verify(harness.target, times(2)).onResourceReady(eq(harness.result), anyTransition()); }
@Test public void testHandlesUpToFiveRedirects() throws Exception { int numRedirects = 4; String expected = "redirectedData"; String redirectBase = "/redirect"; for (int i = 0; i < numRedirects; i++) { mockWebServer.enqueue(new MockResponse().setResponseCode(301) .setHeader("Location", mockWebServer.url(redirectBase + i).toString())); } mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(expected)); getFetcher().loadData(Priority.NORMAL, callback); verify(callback).onDataReady(streamCaptor.capture()); TestUtil.assertStreamOf(expected, streamCaptor.getValue()); assertThat(mockWebServer.takeRequest().getPath()).contains(DEFAULT_PATH); for (int i = 0; i < numRedirects; i++) { assertThat(mockWebServer.takeRequest().getPath()).contains(redirectBase + i); } }
@Override protected void convert(BaseViewHolder helper, LikeBean item) { helper.setText(R.id.txt_like_title, item.getTitle()); if (item.getType() == Constants.TYPE_WEIXIN) { helper.setText(R.id.txt_like_type, R.string.weixin); } else if(item.getType() == Constants.TYPE_GANK){ helper.setText(R.id.txt_like_type, R.string.gank); } helper.setText(R.id.txt_like_date, DateUtil.LongToString(item.getTime())); GlideApp.with(mContext) .load(item.getImageUrl()) .centerCrop() .placeholder(R.drawable.ic_ali) .priority(Priority.LOW) .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC) .into((ImageView) helper.getView(R.id.img_like)); }
private void replaceImage(final String imageName) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; File imageFile = new File(mView.getActivity().getExternalFilesDir(mNoteId).getPath() + "/" + imageName); BitmapFactory.decodeFile(imageFile.getPath(), options); int imageRequestWidth = getRequestImeWidth(); int imageRequestHeight = setNeedHeight(options); Glide.with(mView.getActivity()) .load(imageFile) .asBitmap() .override(imageRequestWidth, imageRequestHeight) .fitCenter() .priority(Priority.HIGH) .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { mView.replaceImage(imageName, resource); } }); }
@BindingAdapter({"imageAddress"}) public static void loadImage(final ImageView imageView, final String imageAddress) { if (imageAddress != null && imageAddress.startsWith("https://s3.amazonaws.com/bikedeboa/")) { Context context = imageView.getContext(); // Hopefully the thumbnail is already disk cached and no requests are made DrawableRequestBuilder<String> thumbnailRequest = Glide .with(context) .load(imageAddress.replace("images/", "images/thumbs/")) .diskCacheStrategy(DiskCacheStrategy.ALL) .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) .transform(new BlurTransformation(context)); Glide.with(context) .load(imageAddress) .thumbnail(thumbnailRequest) .crossFade() .diskCacheStrategy(DiskCacheStrategy.SOURCE) .priority(Priority.HIGH) .into(imageView); } }
@Override public void loadData(Priority priority, DataCallback<? super InputStream> callback) { try { mInputStream = openThumbInputStream(); } catch (FileNotFoundException e) { LogUtils.d(TAG, "Failed to find thumbnail file," + e.toString()); callback.onLoadFailed(e); return; } callback.onDataReady(mInputStream); }
@Override public void loadData(Priority priority, DataCallback<? super Data> callback) { try { data = reader.decode(dataUri); callback.onDataReady(data); } catch (IllegalArgumentException e) { callback.onLoadFailed(e); } }
private static Request.Priority glideToVolleyPriority(Priority priority) { switch (priority) { case LOW: return Request.Priority.LOW; case HIGH: return Request.Priority.HIGH; case IMMEDIATE: return Request.Priority.IMMEDIATE; default: return Request.Priority.NORMAL; } }
@Test public void testDecode() throws IOException { byte[] expected = Base64 .decode(VALID_PNG.substring(VALID_PNG.indexOf(',') + 1), Base64.DEFAULT); CallBack callback = new CallBack(); fetcher.loadData(Priority.HIGH, callback); byte[] result = new byte[((ByteArrayInputStream) callback.data).available()]; assertEquals(result.length, ((ByteArrayInputStream) callback.data).read(result)); assertTrue(Arrays.equals(result, expected)); assertNull(callback.exception); }
public GlideRequest(String url, DataCallback<? super InputStream> callback, Priority priority, Map<String, String> headers) { super(Method.GET, url, null); this.callback = callback; this.priority = priority; this.headers = headers; }
/** * @see GlideOptions#priority(Priority) */ @CheckResult public GlideRequest<TranscodeType> priority(@NonNull Priority arg0) { if (getMutableOptions() instanceof GlideOptions) { this.requestOptions = ((GlideOptions) getMutableOptions()).priority(arg0); } else { this.requestOptions = new GlideOptions().apply(this.requestOptions).priority(arg0); } return this; }
@Test public void testReturnsInputStreamOnStatusOk() throws Exception { String expected = "fakedata"; mockWebServer.enqueue(new MockResponse().setBody(expected).setResponseCode(200)); DataFetcher<InputStream> fetcher = getFetcher(); fetcher.loadData(Priority.HIGH, callback); waitForResponseLatch.await(); verify(callback).onDataReady(streamCaptor.capture()); assertStreamOf(expected, streamCaptor.getValue()); }
@Test public void testIgnoresOnSizeReadyIfNotWaitingForSize() { SingleRequest<List> request = builder.build(); request.begin(); request.onSizeReady(100, 100); request.onSizeReady(100, 100); verify(builder.engine, times(1)) .load( eq(builder.glideContext), eq(builder.model), eq(builder.signature), eq(100), eq(100), eq(Object.class), eq(List.class), any(Priority.class), any(DiskCacheStrategy.class), eq(builder.transformations), anyBoolean(), anyBoolean(), any(Options.class), anyBoolean(), anyBoolean(), /*useAnimationPool=*/ anyBoolean(), anyBoolean(), any(ResourceCallback.class)); }
@Test public void testCallsLoadFailedIfStatusCodeIsNegativeOne() throws Exception { mockWebServer.enqueue(new MockResponse().setResponseCode(-1)); getFetcher().loadData(Priority.LOW, callback); waitForResponseLatch.await(); verify(callback).onLoadFailed(isA(VolleyError.class)); }
@Test public void testCallsLoadFailedAfterTooManyRedirects() throws Exception { for (int i = 0; i < 20; i++) { mockWebServer.enqueue(new MockResponse().setResponseCode(301) .setHeader("Location", mockWebServer.url("/redirect" + i).toString())); } getFetcher().loadData(Priority.NORMAL, callback); waitForResponseLatch.await(); verify(callback).onLoadFailed(isA(VolleyError.class)); }
@Test public void testCancelDoesNotDisconnectIfAlreadyConnected() throws IOException { fetcher.loadData(Priority.HIGH, callback); fetcher.cancel(); verify(urlConnection, never()).disconnect(); }
@Override public void loadImage(Context context, int resizeX, int resizeY, ImageView imageView, Uri uri) { Glide.with(context) .load(uri) .override(resizeX, resizeY) .priority(Priority.HIGH) .into(imageView); }
private static RequestOptions getRequestOptions() { RequestOptions requestOptions = new RequestOptions() .centerCrop() // 填充方式 .priority(Priority.HIGH) //优先级 .diskCacheStrategy(DiskCacheStrategy.ALL); //缓存策略 return requestOptions; }
public DrawableRequestBuilder<GlideDrawable> build() { //noinspection unchecked return createBaseRequest(requestManager, artist, noCustomImage, forceDownload) .diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY) .error(DEFAULT_ERROR_IMAGE) .animate(DEFAULT_ANIMATION) .priority(Priority.LOW) .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) .signature(createSignature(artist)); }
private void init( GlideContext glideContext, Object model, Class<R> transcodeClass, RequestOptions requestOptions, int overrideWidth, int overrideHeight, Priority priority, Target<R> target, RequestListener<R> requestListener, RequestCoordinator requestCoordinator, Engine engine, TransitionFactory<? super R> animationFactory) { this.glideContext = glideContext; this.model = model; this.transcodeClass = transcodeClass; this.requestOptions = requestOptions; this.overrideWidth = overrideWidth; this.overrideHeight = overrideHeight; this.priority = priority; this.target = target; this.requestListener = requestListener; this.requestCoordinator = requestCoordinator; this.engine = engine; this.animationFactory = animationFactory; status = Status.PENDING; }
@Test public void testCallsLoadFailedIfStatusCodeIs400() throws Exception { mockWebServer.enqueue(new MockResponse().setResponseCode(400).setBody("error")); getFetcher().loadData(Priority.LOW, callback); waitForResponseLatch.await(); verify(callback).onLoadFailed(isA(VolleyError.class)); }
@Override public void displayImage(Context context, String path, ImageView imageView) { Glide.with(context) .load(path) .placeholder(R.drawable.global_img_default) .priority(Priority.HIGH) .into(imageView); }
@SuppressWarnings("unchecked") <R> DecodeHelper<R> init( GlideContext glideContext, Object model, Key signature, int width, int height, DiskCacheStrategy diskCacheStrategy, Class<?> resourceClass, Class<R> transcodeClass, Priority priority, Options options, Map<Class<?>, Transformation<?>> transformations, boolean isTransformationRequired, DecodeJob.DiskCacheProvider diskCacheProvider) { this.glideContext = glideContext; this.model = model; this.signature = signature; this.width = width; this.height = height; this.diskCacheStrategy = diskCacheStrategy; this.resourceClass = resourceClass; this.diskCacheProvider = diskCacheProvider; this.transcodeClass = (Class<Transcode>) transcodeClass; this.priority = priority; this.options = options; this.transformations = transformations; this.isTransformationRequired = isTransformationRequired; return (DecodeHelper<R>) this; }
@Override public void loadData(Priority priority, DataCallback<? super Data> callback) { try { toWaitOn.await(ConcurrencyHelper.TIMEOUT_MS, ConcurrencyHelper.TIMEOUT_UNIT); } catch (InterruptedException e) { throw new RuntimeException(e); } wrapped.loadData(priority, callback); }
private static <T> InputStream getInputStreamForModel(Context context, T model) throws BitmapDecodingException { try { return Glide.buildStreamModelLoader(model, context) .getResourceFetcher(model, -1, -1) .loadData(Priority.NORMAL); } catch (Exception e) { throw new BitmapDecodingException(e); } }
@Test public void testDisconnectsUrlOnCleanup() throws IOException { fetcher.loadData(Priority.HIGH, callback); fetcher.cleanup(); verify(urlConnection).disconnect(); }
@SuppressWarnings("ConstantConditions") @Override public void onBindViewHolder(@NonNull final ViewHolder holder, int position) { switch (getItemViewType(position)) { case ALBUM: final Album album = (Album) dataSet.get(position); holder.title.setText(album.getTitle()); holder.text.setText(album.getArtistName()); SongGlideRequest.Builder.from(Glide.with(activity), album.safeGetFirstSong()) .checkIgnoreMediaStore(activity).build() .into(holder.image); break; case ARTIST: final Artist artist = (Artist) dataSet.get(position); holder.title.setText(artist.getName()); holder.text.setText(MusicUtil.getArtistInfoString(activity, artist)); Glide.with(activity) .load(new ArtistImage(artist.getName(), false)) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .placeholder(R.drawable.default_artist_image) .animate(android.R.anim.fade_in) .priority(Priority.LOW) .signature(ArtistSignatureUtil.getInstance(activity).getArtistSignature(artist.getName())) .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) .into(holder.image); break; case SONG: final Song song = (Song) dataSet.get(position); holder.title.setText(song.title); holder.text.setText(song.albumName); break; default: holder.title.setText(dataSet.get(position).toString()); break; } }
@Test public void testFailsIfRedirectLocationIsPresentAndEmpty() throws Exception { mockWebServer.enqueue(new MockResponse().setResponseCode(301).setHeader("Location", "")); getFetcher().loadData(Priority.NORMAL, callback); verify(callback).onLoadFailed(isA(IOException.class)); }
@Override public void loadGifImage(Context context, int resizeX, int resizeY, ImageView imageView, Uri uri) { Glide.with(context) .load(uri) .asGif() .override(resizeX, resizeY) .priority(Priority.HIGH) .into(imageView); }