Skip to content

Commit

Permalink
Introduce Network Policy API
Browse files Browse the repository at this point in the history
  • Loading branch information
dnkoutso committed Jan 2, 2015
1 parent 4595597 commit eb60331
Show file tree
Hide file tree
Showing 33 changed files with 329 additions and 125 deletions.
14 changes: 12 additions & 2 deletions picasso/src/main/java/com/squareup/picasso/Action.java
Expand Up @@ -37,6 +37,7 @@ public RequestWeakReference(Action action, M referent, ReferenceQueue<? super M>
final WeakReference<T> target;
final boolean noFade;
final int memoryPolicy;
final int networkPolicy;
final int errorResId;
final Drawable errorDrawable;
final String key;
Expand All @@ -45,13 +46,14 @@ public RequestWeakReference(Action action, M referent, ReferenceQueue<? super M>
boolean willReplay;
boolean cancelled;

Action(Picasso picasso, T target, Request request, int memoryPolicy, boolean noFade,
int errorResId, Drawable errorDrawable, String key, Object tag) {
Action(Picasso picasso, T target, Request request, int memoryPolicy, int networkPolicy,
int errorResId, Drawable errorDrawable, String key, Object tag, boolean noFade) {
this.picasso = picasso;
this.request = request;
this.target =
target == null ? null : new RequestWeakReference<T>(this, target, picasso.referenceQueue);
this.memoryPolicy = memoryPolicy;
this.networkPolicy = networkPolicy;
this.noFade = noFade;
this.errorResId = errorResId;
this.errorDrawable = errorDrawable;
Expand Down Expand Up @@ -87,6 +89,14 @@ boolean willReplay() {
return willReplay;
}

int getMemoryPolicy() {
return memoryPolicy;
}

int getNetworkPolicy() {
return networkPolicy;
}

Picasso getPicasso() {
return picasso;
}
Expand Down
Expand Up @@ -43,7 +43,7 @@ public AssetRequestHandler(Context context) {
&& !uri.getPathSegments().isEmpty() && ANDROID_ASSET.equals(uri.getPathSegments().get(0)));
}

@Override public Result load(Request data) throws IOException {
@Override public Result load(Request data, int networkPolicy) throws IOException {
String filePath = data.uri.toString().substring(ASSET_PREFIX_LENGTH);
return new Result(decodeAsset(data, filePath), DISK);
}
Expand Down
10 changes: 6 additions & 4 deletions picasso/src/main/java/com/squareup/picasso/BitmapHunter.java
Expand Up @@ -60,7 +60,7 @@ class BitmapHunter implements Runnable {
return true;
}

@Override public Result load(Request data) throws IOException {
@Override public Result load(Request data, int networkPolicy) throws IOException {
throw new IllegalStateException("Unrecognized type of request: " + data);
}
};
Expand All @@ -73,6 +73,7 @@ class BitmapHunter implements Runnable {
final String key;
final Request data;
final int memoryPolicy;
final int networkPolicy;
final RequestHandler requestHandler;

Action action;
Expand All @@ -96,7 +97,8 @@ class BitmapHunter implements Runnable {
this.key = action.getKey();
this.data = action.getRequest();
this.priority = action.getPriority();
this.memoryPolicy = action.memoryPolicy;
this.memoryPolicy = action.getMemoryPolicy();
this.networkPolicy = action.getNetworkPolicy();
this.requestHandler = requestHandler;
this.retryCount = requestHandler.getRetryCount();
}
Expand Down Expand Up @@ -152,8 +154,8 @@ Bitmap hunt() throws IOException {
}
}

data.loadFromLocalCacheOnly = (retryCount == 0);
RequestHandler.Result result = requestHandler.load(data);
data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
RequestHandler.Result result = requestHandler.load(data, networkPolicy);
if (result != null) {
bitmap = result.getBitmap();
loadedFrom = result.getLoadedFrom();
Expand Down
Expand Up @@ -70,7 +70,7 @@ class ContactsPhotoRequestHandler extends RequestHandler {
&& !uri.getPathSegments().contains(ContactsContract.Contacts.Photo.CONTENT_DIRECTORY));
}

@Override public Result load(Request data) throws IOException {
@Override public Result load(Request data, int networkPolicy) throws IOException {
InputStream is = null;
try {
is = getInputStream(data);
Expand Down
Expand Up @@ -36,7 +36,7 @@ class ContentStreamRequestHandler extends RequestHandler {
return SCHEME_CONTENT.equals(data.uri.getScheme());
}

@Override public Result load(Request data) throws IOException {
@Override public Result load(Request data, int networkPolicy) throws IOException {
return new Result(decodeContentStream(data), DISK);
}

Expand Down
9 changes: 4 additions & 5 deletions picasso/src/main/java/com/squareup/picasso/Downloader.java
Expand Up @@ -26,14 +26,13 @@ public interface Downloader {
* Download the specified image {@code url} from the internet.
*
* @param uri Remote image URL.
* @param localCacheOnly If {@code true} the URL should only be loaded if available in a local
* disk cache.
* @param networkPolicy The {@link NetworkPolicy} used for this request.
* @return {@link Response} containing either a {@link Bitmap} representation of the request or an
* {@link InputStream} for the image data. {@code null} can be returned to indicate a problem
* loading the bitmap.
* @throws IOException if the requested URL cannot successfully be loaded.
*/
Response load(Uri uri, boolean localCacheOnly) throws IOException;
Response load(Uri uri, int networkPolicy) throws IOException;

/**
* Allows to perform a clean up for this {@link Downloader} including closing the disk cache and
Expand All @@ -46,9 +45,9 @@ class ResponseException extends IOException {
final boolean localCacheOnly;
final int responseCode;

public ResponseException(String message, boolean localCacheOnly, int responseCode) {
public ResponseException(String message, int networkPolicy, int responseCode) {
super(message);
this.localCacheOnly = localCacheOnly;
this.localCacheOnly = NetworkPolicy.isOfflineOnly(networkPolicy);
this.responseCode = responseCode;
}
}
Expand Down
5 changes: 3 additions & 2 deletions picasso/src/main/java/com/squareup/picasso/FetchAction.java
Expand Up @@ -21,8 +21,9 @@ class FetchAction extends Action<Object> {

private final Object target;

FetchAction(Picasso picasso, Request data, int memoryPolicy, String key, Object tag) {
super(picasso, null, data, memoryPolicy, false, 0, null, key, tag);
FetchAction(Picasso picasso, Request data, int memoryPolicy, int networkPolicy, Object tag,
String key) {
super(picasso, null, data, memoryPolicy, networkPolicy, 0, null, key, tag, false);
this.target = new Object();
}

Expand Down
Expand Up @@ -38,7 +38,7 @@ class FileRequestHandler extends ContentStreamRequestHandler {
return SCHEME_FILE.equals(data.uri.getScheme());
}

@Override public Result load(Request data) throws IOException {
@Override public Result load(Request data, int networkPolicy) throws IOException {
return new Result(decodeContentStream(data), DISK, getFileExifRotation(data.uri));
}

Expand Down
5 changes: 3 additions & 2 deletions picasso/src/main/java/com/squareup/picasso/GetAction.java
Expand Up @@ -18,8 +18,9 @@
import android.graphics.Bitmap;

class GetAction extends Action<Void> {
GetAction(Picasso picasso, Request data, int memoryPolicy, String key, Object tag) {
super(picasso, null, data, memoryPolicy, false, 0, null, key, tag);
GetAction(Picasso picasso, Request data, int memoryPolicy, int networkPolicy, Object tag,
String key) {
super(picasso, null, data, memoryPolicy, networkPolicy, 0, null, key, tag, false);
}

@Override void complete(Bitmap result, Picasso.LoadedFrom from) {
Expand Down
Expand Up @@ -25,9 +25,10 @@ class ImageViewAction extends Action<ImageView> {
Callback callback;

ImageViewAction(Picasso picasso, ImageView imageView, Request data, int memoryPolicy,
boolean noFade, int errorResId, Drawable errorDrawable, String key, Object tag,
Callback callback) {
super(picasso, imageView, data, memoryPolicy, noFade, errorResId, errorDrawable, key, tag);
int networkPolicy, int errorResId, Drawable errorDrawable, String key, Object tag,
Callback callback, boolean noFade) {
super(picasso, imageView, data, memoryPolicy, networkPolicy, errorResId, errorDrawable, key,
tag, noFade);
this.callback = callback;
}

Expand Down
Expand Up @@ -51,7 +51,7 @@ class MediaStoreRequestHandler extends ContentStreamRequestHandler {
&& MediaStore.AUTHORITY.equals(uri.getAuthority()));
}

@Override public Result load(Request data) throws IOException {
@Override public Result load(Request data, int networkPolicy) throws IOException {
ContentResolver contentResolver = context.getContentResolver();
int exifOrientation = getExifOrientation(contentResolver, data.uri);

Expand Down
36 changes: 36 additions & 0 deletions picasso/src/main/java/com/squareup/picasso/NetworkPolicy.java
@@ -0,0 +1,36 @@
package com.squareup.picasso;

/** Designates the policy to use for network requests. */
@SuppressWarnings("PointlessBitwiseExpression")
public enum NetworkPolicy {

/** Skips checking the disk cache and forces loading through the network. */
NO_CACHE(1 << 0),

/** Skips storing the result into the disk cache.
* <p>
* <em>Note</em>: At this time this is only supported if you are using OkHttp.
*/
NO_STORE(1 << 1),

/** Forces the request through the disk cache only, skipping network. */
OFFLINE(1 << 2);

public static boolean shouldReadFromDiskCache(int networkPolicy) {
return (networkPolicy & NetworkPolicy.NO_CACHE.index) == 0;
}

public static boolean shouldWriteToDiskCache(int networkPolicy) {
return (networkPolicy & NetworkPolicy.NO_STORE.index) == 0;
}

public static boolean isOfflineOnly(int networkPolicy) {
return (networkPolicy & NetworkPolicy.OFFLINE.index) != 0;
}

final int index;

private NetworkPolicy(int index) {
this.index = index;
}
}
Expand Up @@ -45,8 +45,8 @@ public NetworkRequestHandler(Downloader downloader, Stats stats) {
return (SCHEME_HTTP.equals(scheme) || SCHEME_HTTPS.equals(scheme));
}

@Override public Result load(Request data) throws IOException {
Response response = downloader.load(data.uri, data.loadFromLocalCacheOnly);
@Override public Result load(Request data, int networkPolicy) throws IOException {
Response response = downloader.load(data.uri, data.networkPolicy);
if (response == null) {
return null;
}
Expand Down
30 changes: 23 additions & 7 deletions picasso/src/main/java/com/squareup/picasso/OkHttpDownloader.java
Expand Up @@ -17,8 +17,10 @@

import android.content.Context;
import android.net.Uri;
import com.squareup.okhttp.CacheControl;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.ResponseBody;
import com.squareup.okhttp.Request;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
Expand Down Expand Up @@ -90,19 +92,33 @@ protected final OkHttpClient getClient() {
return client;
}

@Override public Response load(Uri uri, boolean localCacheOnly) throws IOException {
com.squareup.okhttp.Request.Builder requestBuilder =
new com.squareup.okhttp.Request.Builder().url(uri.toString());
@Override public Response load(Uri uri, int networkPolicy) throws IOException {
CacheControl cacheControl = null;
if (networkPolicy != 0) {
if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
cacheControl = CacheControl.FORCE_CACHE;
} else {
CacheControl.Builder builder = new CacheControl.Builder();
if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {
builder.noCache();
}
if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
builder.noStore();
}
cacheControl = builder.build();
}
}

if (localCacheOnly) {
requestBuilder.addHeader("Cache-Control", "only-if-cached,max-age=2147483647");
Request.Builder builder = new Request.Builder().url(uri.toString());
if (cacheControl != null) {
builder.cacheControl(cacheControl);
}

com.squareup.okhttp.Response response = client.newCall(requestBuilder.build()).execute();
com.squareup.okhttp.Response response = client.newCall(builder.build()).execute();
int responseCode = response.code();
if (responseCode >= 300) {
response.body().close();
throw new ResponseException(responseCode + " " + response.message(), localCacheOnly,
throw new ResponseException(responseCode + " " + response.message(), networkPolicy,
responseCode);
}

Expand Down
Expand Up @@ -31,8 +31,8 @@ abstract class RemoteViewsAction extends Action<RemoteViewsAction.RemoteViewsTar
private RemoteViewsTarget target;

RemoteViewsAction(Picasso picasso, Request data, RemoteViews remoteViews, int viewId,
int errorResId, int memoryPolicy, String key, Object tag) {
super(picasso, null, data, memoryPolicy, false, errorResId, null, key, tag);
int errorResId, int memoryPolicy, int networkPolicy, Object tag, String key) {
super(picasso, null, data, memoryPolicy, networkPolicy, errorResId, null, key, tag, false);
this.remoteViews = remoteViews;
this.viewId = viewId;
}
Expand Down Expand Up @@ -88,8 +88,9 @@ static class AppWidgetAction extends RemoteViewsAction {
private final int[] appWidgetIds;

AppWidgetAction(Picasso picasso, Request data, RemoteViews remoteViews, int viewId,
int[] appWidgetIds, int memoryPolicy, int errorResId, String key, Object tag) {
super(picasso, data, remoteViews, viewId, errorResId, memoryPolicy, key, tag);
int[] appWidgetIds, int memoryPolicy, int networkPolicy, String key, Object tag,
int errorResId) {
super(picasso, data, remoteViews, viewId, errorResId, memoryPolicy, networkPolicy, tag, key);
this.appWidgetIds = appWidgetIds;
}

Expand All @@ -104,9 +105,9 @@ static class NotificationAction extends RemoteViewsAction {
private final Notification notification;

NotificationAction(Picasso picasso, Request data, RemoteViews remoteViews, int viewId,
int notificationId, Notification notification, int memoryPolicy, int errorResId,
String key, Object tag) {
super(picasso, data, remoteViews, viewId, errorResId, memoryPolicy, key, tag);
int notificationId, Notification notification, int memoryPolicy, int networkPolicy,
String key, Object tag, int errorResId) {
super(picasso, data, remoteViews, viewId, errorResId, memoryPolicy, networkPolicy, tag, key);
this.notificationId = notificationId;
this.notification = notification;
}
Expand Down
4 changes: 2 additions & 2 deletions picasso/src/main/java/com/squareup/picasso/Request.java
Expand Up @@ -32,8 +32,8 @@ public final class Request {
int id;
/** The time that the request was first submitted (in nanos). */
long started;
/** Whether or not this request should only load from local cache. */
boolean loadFromLocalCacheOnly;
/** The {@link NetworkPolicy} to use for this request. */
int networkPolicy;

/**
* The image URI.
Expand Down

0 comments on commit eb60331

Please sign in to comment.