diff options
author | Anonymous <no-reply@google.com> | 2018-05-07 11:39:31 -0700 |
---|---|---|
committer | Jeff Davidson <jpd@google.com> | 2018-05-10 20:11:47 +0000 |
commit | 9a128540048414c78a2be9524f93b6234c640b3a (patch) | |
tree | f39fa51c442a9c6922d1f6def2e75d5dca677f20 /src/main/java/com/android/volley/toolbox | |
parent | aee0d184daa41c0abb5bf88580ad6cf7fea63d72 (diff) | |
download | volley-9a128540048414c78a2be9524f93b6234c640b3a.tar.gz |
Import of Volley from GitHub to AOSP.android-o-mr1-iot-release-1.0.1
Adds android-support-annotations as a runtime dependency in Android.mk.
- 28588322fa4eca3c1a7922b8a2f7b4a97d5c099a Fix concurrent modification errors in ImageContainer. (#1... by Jeff Davidson <jpd236@cornell.edu>
- ba3b40457a97b3b3812cb00191b41cb0af4149df Fix unchecked operations in Volley build. (#178) by Jeff Davidson <jpd236@cornell.edu>
- 62c19019e43a76ba4a084b25548e7fb1cfd4a457 Always close HttpURLConnections in HurlStack. (#176) by Jeff Davidson <jpd236@cornell.edu>
- 36c80f25a78cf2ba2feb2d697f12f9bbca96bf43 Port dispatcher tests to mockito. (#172) by Jeff Davidson <jpd236@cornell.edu>
- 15b55093fc8ac86902a745f46a2bdea825e797a3 Cleaning up parameter comments + unnecessary generics. (#... by Jeff Davidson <jpd236@cornell.edu>
- 6b341755e522f23de149544536b9b69c7b7b8305 Remove all wildcard imports. (#170) by Jeff Davidson <jpd236@cornell.edu>
- a8424005b3ba6d17fc9e123a2176da702f3ead10 Use actual annotations instead of comments. (#169) by Jeff Davidson <jpd236@cornell.edu>
- bdc80555aee738235bd33c26878bbe8ce382d795 Apply google-java-format to all code. (#165) by Jeff Davidson <jpd236@cornell.edu>
- 5307293b15dd0c32f53b8f1fd8c198caa443982e Integrate Volley builds with errorprone. (#162) by Jeff Davidson <jpd236@cornell.edu>
- fa586029500e6813d654f1b454cd3345b0a43897 Fail Travis builds if snapshot uploading fails. (#163) by Jeff Davidson <jpd236@cornell.edu>
- 0ebb97e9b0192e879088b38b5992158e99364dc6 Stop publishing bintray-info.json. (#141) by Jeff Davidson <jpd236@cornell.edu>
- b89dfbd2e6964acfe5561e268300611a83957a15 fix: request time contains RequestQueue blocking time. (#... by dezng <dezng123@gmail.com>
- c2bfd86596e588c924c2c7e0ae0940053800af5c Guard against illegal argument and OOM exceptions in read... by Joe Bowbeer <joe.bowbeer@gmail.com>
- fc8ff0423fe9a3af6595088b34f912fb2d920ffb Log fix (#112) by Navid Ht <navid.htb@gmail.com>
- 47586f0fd42acd5ce09dfc767387df685edfa547 Bump version to 1.1.1-SNAPSHOT. (#123) by Jeff Davidson <jpd236@cornell.edu>
- 1392f961af17d0f5ba367d8d199a18e5325b882e Update deploy credentials. (#122) by Jeff Davidson <jpd236@cornell.edu>
- ffe9281709f38f84492ce898603d3ec084326a57 Set project group and version. (#120) by Jeff Davidson <jpd236@cornell.edu>
GitOrigin-RevId: 28588322fa4eca3c1a7922b8a2f7b4a97d5c099a
Change-Id: Ifeea069df2f0a5fd10bc3d4686601c88906ee653
Diffstat (limited to 'src/main/java/com/android/volley/toolbox')
25 files changed, 785 insertions, 673 deletions
diff --git a/src/main/java/com/android/volley/toolbox/AdaptedHttpStack.java b/src/main/java/com/android/volley/toolbox/AdaptedHttpStack.java index e5dc62b..c75c25f 100644 --- a/src/main/java/com/android/volley/toolbox/AdaptedHttpStack.java +++ b/src/main/java/com/android/volley/toolbox/AdaptedHttpStack.java @@ -18,14 +18,12 @@ package com.android.volley.toolbox; import com.android.volley.AuthFailureError; import com.android.volley.Header; import com.android.volley.Request; - -import org.apache.http.conn.ConnectTimeoutException; - import java.io.IOException; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.apache.http.conn.ConnectTimeoutException; /** * {@link BaseHttpStack} implementation wrapping a {@link HttpStack}. @@ -43,12 +41,11 @@ class AdaptedHttpStack extends BaseHttpStack { } @Override - public HttpResponse executeRequest( - Request<?> request, Map<String, String> additionalHeaders) + public HttpResponse executeRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { org.apache.http.HttpResponse apacheResp; try { - apacheResp = mHttpStack.performRequest(request, additionalHeaders); + apacheResp = mHttpStack.performRequest(request, additionalHeaders); } catch (ConnectTimeoutException e) { // BasicNetwork won't know that this exception should be retried like a timeout, since // it's an Apache-specific error, so wrap it in a standard timeout exception. diff --git a/src/main/java/com/android/volley/toolbox/AndroidAuthenticator.java b/src/main/java/com/android/volley/toolbox/AndroidAuthenticator.java index 73468b9..72271fc 100644 --- a/src/main/java/com/android/volley/toolbox/AndroidAuthenticator.java +++ b/src/main/java/com/android/volley/toolbox/AndroidAuthenticator.java @@ -16,8 +16,6 @@ package com.android.volley.toolbox; -import com.android.volley.AuthFailureError; - import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerFuture; @@ -25,10 +23,12 @@ import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.os.Bundle; +import android.support.annotation.VisibleForTesting; +import com.android.volley.AuthFailureError; /** - * An Authenticator that uses {@link AccountManager} to get auth - * tokens of a specified type for a specified account. + * An Authenticator that uses {@link AccountManager} to get auth tokens of a specified type for a + * specified account. */ // TODO: Update this to account for runtime permissions @SuppressLint("MissingPermission") @@ -40,45 +40,46 @@ public class AndroidAuthenticator implements Authenticator { /** * Creates a new authenticator. + * * @param context Context for accessing AccountManager * @param account Account to authenticate as * @param authTokenType Auth token type passed to AccountManager */ public AndroidAuthenticator(Context context, Account account, String authTokenType) { - this(context, account, authTokenType, false); + this(context, account, authTokenType, /* notifyAuthFailure= */ false); } /** * Creates a new authenticator. + * * @param context Context for accessing AccountManager * @param account Account to authenticate as * @param authTokenType Auth token type passed to AccountManager * @param notifyAuthFailure Whether to raise a notification upon auth failure */ - public AndroidAuthenticator(Context context, Account account, String authTokenType, - boolean notifyAuthFailure) { + public AndroidAuthenticator( + Context context, Account account, String authTokenType, boolean notifyAuthFailure) { this(AccountManager.get(context), account, authTokenType, notifyAuthFailure); } - // Visible for testing. Allows injection of a mock AccountManager. - AndroidAuthenticator(AccountManager accountManager, Account account, - String authTokenType, boolean notifyAuthFailure) { + @VisibleForTesting + AndroidAuthenticator( + AccountManager accountManager, + Account account, + String authTokenType, + boolean notifyAuthFailure) { mAccountManager = accountManager; mAccount = account; mAuthTokenType = authTokenType; mNotifyAuthFailure = notifyAuthFailure; } - /** - * Returns the Account being used by this authenticator. - */ + /** Returns the Account being used by this authenticator. */ public Account getAccount() { return mAccount; } - /** - * Returns the Auth Token Type used by this authenticator. - */ + /** Returns the Auth Token Type used by this authenticator. */ public String getAuthTokenType() { return mAuthTokenType; } @@ -87,8 +88,13 @@ public class AndroidAuthenticator implements Authenticator { @SuppressWarnings("deprecation") @Override public String getAuthToken() throws AuthFailureError { - AccountManagerFuture<Bundle> future = mAccountManager.getAuthToken(mAccount, - mAuthTokenType, mNotifyAuthFailure, null, null); + AccountManagerFuture<Bundle> future = + mAccountManager.getAuthToken( + mAccount, + mAuthTokenType, + mNotifyAuthFailure, + /* callback= */ null, + /* handler= */ null); Bundle result; try { result = future.getResult(); diff --git a/src/main/java/com/android/volley/toolbox/Authenticator.java b/src/main/java/com/android/volley/toolbox/Authenticator.java index adfc996..2ba43db 100644 --- a/src/main/java/com/android/volley/toolbox/Authenticator.java +++ b/src/main/java/com/android/volley/toolbox/Authenticator.java @@ -18,9 +18,7 @@ package com.android.volley.toolbox; import com.android.volley.AuthFailureError; -/** - * An interface for interacting with auth tokens. - */ +/** An interface for interacting with auth tokens. */ public interface Authenticator { /** * Synchronously retrieves an auth token. @@ -29,8 +27,6 @@ public interface Authenticator { */ String getAuthToken() throws AuthFailureError; - /** - * Invalidates the provided auth token. - */ + /** Invalidates the provided auth token. */ void invalidateAuthToken(String authToken); } diff --git a/src/main/java/com/android/volley/toolbox/BaseHttpStack.java b/src/main/java/com/android/volley/toolbox/BaseHttpStack.java index 257f75c..4f596e1 100644 --- a/src/main/java/com/android/volley/toolbox/BaseHttpStack.java +++ b/src/main/java/com/android/volley/toolbox/BaseHttpStack.java @@ -18,20 +18,18 @@ package com.android.volley.toolbox; import com.android.volley.AuthFailureError; import com.android.volley.Header; import com.android.volley.Request; - -import org.apache.http.ProtocolVersion; -import org.apache.http.StatusLine; -import org.apache.http.entity.BasicHttpEntity; -import org.apache.http.message.BasicHeader; -import org.apache.http.message.BasicHttpResponse; -import org.apache.http.message.BasicStatusLine; - import java.io.IOException; import java.io.InputStream; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.apache.http.ProtocolVersion; +import org.apache.http.StatusLine; +import org.apache.http.entity.BasicHttpEntity; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicHttpResponse; +import org.apache.http.message.BasicStatusLine; /** An HTTP stack abstraction. */ @SuppressWarnings("deprecation") // for HttpStack @@ -44,8 +42,8 @@ public abstract class BaseHttpStack implements HttpStack { * and the Content-Type header is set to request.getPostBodyContentType(). * * @param request the request to perform - * @param additionalHeaders additional headers to be sent together with - * {@link Request#getHeaders()} + * @param additionalHeaders additional headers to be sent together with {@link + * Request#getHeaders()} * @return the {@link HttpResponse} * @throws SocketTimeoutException if the request times out * @throws IOException if another I/O error occurs during the request @@ -57,10 +55,10 @@ public abstract class BaseHttpStack implements HttpStack { /** * @deprecated use {@link #executeRequest} instead to avoid a dependency on the deprecated - * Apache HTTP library. Nothing in Volley's own source calls this method. However, since - * {@link BasicNetwork#mHttpStack} is exposed to subclasses, we provide this implementation in - * case legacy client apps are dependent on that field. This method may be removed in a future - * release of Volley. + * Apache HTTP library. Nothing in Volley's own source calls this method. However, since + * {@link BasicNetwork#mHttpStack} is exposed to subclasses, we provide this implementation + * in case legacy client apps are dependent on that field. This method may be removed in a + * future release of Volley. */ @Deprecated @Override @@ -70,8 +68,9 @@ public abstract class BaseHttpStack implements HttpStack { HttpResponse response = executeRequest(request, additionalHeaders); ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); - StatusLine statusLine = new BasicStatusLine( - protocolVersion, response.getStatusCode(), "" /* reasonPhrase */); + StatusLine statusLine = + new BasicStatusLine( + protocolVersion, response.getStatusCode(), /* reasonPhrase= */ ""); BasicHttpResponse apacheResponse = new BasicHttpResponse(statusLine); List<org.apache.http.Header> headers = new ArrayList<>(); diff --git a/src/main/java/com/android/volley/toolbox/BasicNetwork.java b/src/main/java/com/android/volley/toolbox/BasicNetwork.java index 5330733..b527cb9 100644 --- a/src/main/java/com/android/volley/toolbox/BasicNetwork.java +++ b/src/main/java/com/android/volley/toolbox/BasicNetwork.java @@ -17,7 +17,6 @@ package com.android.volley.toolbox; import android.os.SystemClock; - import com.android.volley.AuthFailureError; import com.android.volley.Cache; import com.android.volley.Cache.Entry; @@ -33,7 +32,6 @@ import com.android.volley.ServerError; import com.android.volley.TimeoutError; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; - import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; @@ -48,9 +46,7 @@ import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; -/** - * A network performing Volley requests over an {@link HttpStack}. - */ +/** A network performing Volley requests over an {@link HttpStack}. */ public class BasicNetwork implements Network { protected static final boolean DEBUG = VolleyLog.DEBUG; @@ -60,10 +56,9 @@ public class BasicNetwork implements Network { /** * @deprecated Should never have been exposed in the API. This field may be removed in a future - * release of Volley. + * release of Volley. */ - @Deprecated - protected final HttpStack mHttpStack; + @Deprecated protected final HttpStack mHttpStack; private final BaseHttpStack mBaseHttpStack; @@ -72,7 +67,7 @@ public class BasicNetwork implements Network { /** * @param httpStack HTTP stack to be used * @deprecated use {@link #BasicNetwork(BaseHttpStack)} instead to avoid depending on Apache - * HTTP. This method may be removed in a future release of Volley. + * HTTP. This method may be removed in a future release of Volley. */ @Deprecated public BasicNetwork(HttpStack httpStack) { @@ -85,8 +80,7 @@ public class BasicNetwork implements Network { * @param httpStack HTTP stack to be used * @param pool a buffer pool that improves GC performance in copy operations * @deprecated use {@link #BasicNetwork(BaseHttpStack, ByteArrayPool)} instead to avoid - * depending on Apache HTTP. This method may be removed in a future release of - * Volley. + * depending on Apache HTTP. This method may be removed in a future release of Volley. */ @Deprecated public BasicNetwork(HttpStack httpStack, ByteArrayPool pool) { @@ -95,9 +89,7 @@ public class BasicNetwork implements Network { mPool = pool; } - /** - * @param httpStack HTTP stack to be used - */ + /** @param httpStack HTTP stack to be used */ public BasicNetwork(BaseHttpStack httpStack) { // If a pool isn't passed in, then build a small default pool that will give us a lot of // benefit and not use too much memory. @@ -136,24 +128,32 @@ public class BasicNetwork implements Network { if (statusCode == HttpURLConnection.HTTP_NOT_MODIFIED) { Entry entry = request.getCacheEntry(); if (entry == null) { - return new NetworkResponse(HttpURLConnection.HTTP_NOT_MODIFIED, null, true, - SystemClock.elapsedRealtime() - requestStart, responseHeaders); + return new NetworkResponse( + HttpURLConnection.HTTP_NOT_MODIFIED, + /* data= */ null, + /* notModified= */ true, + SystemClock.elapsedRealtime() - requestStart, + responseHeaders); } // Combine cached and response headers so the response will be complete. List<Header> combinedHeaders = combineHeaders(responseHeaders, entry); - return new NetworkResponse(HttpURLConnection.HTTP_NOT_MODIFIED, entry.data, - true, SystemClock.elapsedRealtime() - requestStart, combinedHeaders); + return new NetworkResponse( + HttpURLConnection.HTTP_NOT_MODIFIED, + entry.data, + /* notModified= */ true, + SystemClock.elapsedRealtime() - requestStart, + combinedHeaders); } // Some responses such as 204s do not have content. We must check. InputStream inputStream = httpResponse.getContent(); if (inputStream != null) { - responseContents = - inputStreamToBytes(inputStream, httpResponse.getContentLength()); + responseContents = + inputStreamToBytes(inputStream, httpResponse.getContentLength()); } else { - // Add 0 byte response as a way of honestly representing a - // no-content request. - responseContents = new byte[0]; + // Add 0 byte response as a way of honestly representing a + // no-content request. + responseContents = new byte[0]; } // if the request is slow, log it. @@ -163,8 +163,12 @@ public class BasicNetwork implements Network { if (statusCode < 200 || statusCode > 299) { throw new IOException(); } - return new NetworkResponse(statusCode, responseContents, false, - SystemClock.elapsedRealtime() - requestStart, responseHeaders); + return new NetworkResponse( + statusCode, + responseContents, + /* notModified= */ false, + SystemClock.elapsedRealtime() - requestStart, + responseHeaders); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new TimeoutError()); } catch (MalformedURLException e) { @@ -179,19 +183,24 @@ public class BasicNetwork implements Network { VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl()); NetworkResponse networkResponse; if (responseContents != null) { - networkResponse = new NetworkResponse(statusCode, responseContents, false, - SystemClock.elapsedRealtime() - requestStart, responseHeaders); - if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED || - statusCode == HttpURLConnection.HTTP_FORBIDDEN) { - attemptRetryOnException("auth", - request, new AuthFailureError(networkResponse)); + networkResponse = + new NetworkResponse( + statusCode, + responseContents, + /* notModified= */ false, + SystemClock.elapsedRealtime() - requestStart, + responseHeaders); + if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED + || statusCode == HttpURLConnection.HTTP_FORBIDDEN) { + attemptRetryOnException( + "auth", request, new AuthFailureError(networkResponse)); } else if (statusCode >= 400 && statusCode <= 499) { // Don't retry other client errors. throw new ClientError(networkResponse); } else if (statusCode >= 500 && statusCode <= 599) { if (request.shouldRetryServerErrors()) { - attemptRetryOnException("server", - request, new ServerError(networkResponse)); + attemptRetryOnException( + "server", request, new ServerError(networkResponse)); } else { throw new ServerError(networkResponse); } @@ -206,26 +215,29 @@ public class BasicNetwork implements Network { } } - /** - * Logs requests that took over SLOW_REQUEST_THRESHOLD_MS to complete. - */ - private void logSlowRequests(long requestLifetime, Request<?> request, - byte[] responseContents, int statusCode) { + /** Logs requests that took over SLOW_REQUEST_THRESHOLD_MS to complete. */ + private void logSlowRequests( + long requestLifetime, Request<?> request, byte[] responseContents, int statusCode) { if (DEBUG || requestLifetime > SLOW_REQUEST_THRESHOLD_MS) { - VolleyLog.d("HTTP response for request=<%s> [lifetime=%d], [size=%s], " + - "[rc=%d], [retryCount=%s]", request, requestLifetime, + VolleyLog.d( + "HTTP response for request=<%s> [lifetime=%d], [size=%s], " + + "[rc=%d], [retryCount=%s]", + request, + requestLifetime, responseContents != null ? responseContents.length : "null", - statusCode, request.getRetryPolicy().getCurrentRetryCount()); + statusCode, + request.getRetryPolicy().getCurrentRetryCount()); } } /** * Attempts to prepare the request for a retry. If there are no more attempts remaining in the * request's retry policy, a timeout exception is thrown. + * * @param request The request to use. */ - private static void attemptRetryOnException(String logPrefix, Request<?> request, - VolleyError exception) throws VolleyError { + private static void attemptRetryOnException( + String logPrefix, Request<?> request, VolleyError exception) throws VolleyError { RetryPolicy retryPolicy = request.getRetryPolicy(); int oldTimeout = request.getTimeoutMs(); @@ -252,8 +264,8 @@ public class BasicNetwork implements Network { } if (entry.lastModified > 0) { - headers.put("If-Modified-Since", - HttpHeaderParser.formatEpochAsRfc1123(entry.lastModified)); + headers.put( + "If-Modified-Since", HttpHeaderParser.formatEpochAsRfc1123(entry.lastModified)); } return headers; @@ -267,8 +279,7 @@ public class BasicNetwork implements Network { /** Reads the contents of an InputStream into a byte[]. */ private byte[] inputStreamToBytes(InputStream in, int contentLength) throws IOException, ServerError { - PoolingByteArrayOutputStream bytes = - new PoolingByteArrayOutputStream(mPool, contentLength); + PoolingByteArrayOutputStream bytes = new PoolingByteArrayOutputStream(mPool, contentLength); byte[] buffer = null; try { if (in == null) { @@ -300,7 +311,7 @@ public class BasicNetwork implements Network { * Converts Headers[] to Map<String, String>. * * @deprecated Should never have been exposed in the API. This method may be removed in a future - * release of Volley. + * release of Volley. */ @Deprecated protected static Map<String, String> convertHeaders(Header[] headers) { @@ -325,8 +336,7 @@ public class BasicNetwork implements Network { private static List<Header> combineHeaders(List<Header> responseHeaders, Entry entry) { // First, create a case-insensitive set of header names from the network // response. - Set<String> headerNamesFromNetworkResponse = - new TreeSet<>(String.CASE_INSENSITIVE_ORDER); + Set<String> headerNamesFromNetworkResponse = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); if (!responseHeaders.isEmpty()) { for (Header header : responseHeaders) { headerNamesFromNetworkResponse.add(header.getName()); diff --git a/src/main/java/com/android/volley/toolbox/ByteArrayPool.java b/src/main/java/com/android/volley/toolbox/ByteArrayPool.java index c8ca2c2..0134fa2 100644 --- a/src/main/java/com/android/volley/toolbox/ByteArrayPool.java +++ b/src/main/java/com/android/volley/toolbox/ByteArrayPool.java @@ -19,42 +19,41 @@ package com.android.volley.toolbox; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; -import java.util.LinkedList; import java.util.List; /** - * ByteArrayPool is a source and repository of <code>byte[]</code> objects. Its purpose is to - * supply those buffers to consumers who need to use them for a short period of time and then - * dispose of them. Simply creating and disposing such buffers in the conventional manner can - * considerable heap churn and garbage collection delays on Android, which lacks good management of - * short-lived heap objects. It may be advantageous to trade off some memory in the form of a - * permanently allocated pool of buffers in order to gain heap performance improvements; that is - * what this class does. - * <p> - * A good candidate user for this class is something like an I/O system that uses large temporary - * <code>byte[]</code> buffers to copy data around. In these use cases, often the consumer wants - * the buffer to be a certain minimum size to ensure good performance (e.g. when copying data chunks - * off of a stream), but doesn't mind if the buffer is larger than the minimum. Taking this into - * account and also to maximize the odds of being able to reuse a recycled buffer, this class is - * free to return buffers larger than the requested size. The caller needs to be able to gracefully - * deal with getting buffers any size over the minimum. - * <p> - * If there is not a suitably-sized buffer in its recycling pool when a buffer is requested, this + * ByteArrayPool is a source and repository of <code>byte[]</code> objects. Its purpose is to supply + * those buffers to consumers who need to use them for a short period of time and then dispose of + * them. Simply creating and disposing such buffers in the conventional manner can considerable heap + * churn and garbage collection delays on Android, which lacks good management of short-lived heap + * objects. It may be advantageous to trade off some memory in the form of a permanently allocated + * pool of buffers in order to gain heap performance improvements; that is what this class does. + * + * <p>A good candidate user for this class is something like an I/O system that uses large temporary + * <code>byte[]</code> buffers to copy data around. In these use cases, often the consumer wants the + * buffer to be a certain minimum size to ensure good performance (e.g. when copying data chunks off + * of a stream), but doesn't mind if the buffer is larger than the minimum. Taking this into account + * and also to maximize the odds of being able to reuse a recycled buffer, this class is free to + * return buffers larger than the requested size. The caller needs to be able to gracefully deal + * with getting buffers any size over the minimum. + * + * <p>If there is not a suitably-sized buffer in its recycling pool when a buffer is requested, this * class will allocate a new buffer and return it. - * <p> - * This class has no special ownership of buffers it creates; the caller is free to take a buffer - * it receives from this pool, use it permanently, and never return it to the pool; additionally, - * it is not harmful to return to this pool a buffer that was allocated elsewhere, provided there - * are no other lingering references to it. - * <p> - * This class ensures that the total size of the buffers in its recycling pool never exceeds a + * + * <p>This class has no special ownership of buffers it creates; the caller is free to take a buffer + * it receives from this pool, use it permanently, and never return it to the pool; additionally, it + * is not harmful to return to this pool a buffer that was allocated elsewhere, provided there are + * no other lingering references to it. + * + * <p>This class ensures that the total size of the buffers in its recycling pool never exceeds a * certain byte limit. When a buffer is returned that would cause the pool to exceed the limit, * least-recently-used buffers are disposed. */ public class ByteArrayPool { /** The buffer pool, arranged both by last use and by buffer size */ - private final List<byte[]> mBuffersByLastUse = new LinkedList<byte[]>(); - private final List<byte[]> mBuffersBySize = new ArrayList<byte[]>(64); + private final List<byte[]> mBuffersByLastUse = new ArrayList<>(); + + private final List<byte[]> mBuffersBySize = new ArrayList<>(64); /** The total size of the buffers in the pool */ private int mCurrentSize = 0; @@ -66,16 +65,15 @@ public class ByteArrayPool { private final int mSizeLimit; /** Compares buffers by size */ - protected static final Comparator<byte[]> BUF_COMPARATOR = new Comparator<byte[]>() { - @Override - public int compare(byte[] lhs, byte[] rhs) { - return lhs.length - rhs.length; - } - }; + protected static final Comparator<byte[]> BUF_COMPARATOR = + new Comparator<byte[]>() { + @Override + public int compare(byte[] lhs, byte[] rhs) { + return lhs.length - rhs.length; + } + }; - /** - * @param sizeLimit the maximum size of the pool, in bytes - */ + /** @param sizeLimit the maximum size of the pool, in bytes */ public ByteArrayPool(int sizeLimit) { mSizeLimit = sizeLimit; } @@ -85,7 +83,7 @@ public class ByteArrayPool { * one if a pooled one is not available. * * @param len the minimum size, in bytes, of the requested buffer. The returned buffer may be - * larger. + * larger. * @return a byte[] buffer is always returned. */ public synchronized byte[] getBuf(int len) { @@ -121,9 +119,7 @@ public class ByteArrayPool { trim(); } - /** - * Removes buffers from the pool until it is under its size limit. - */ + /** Removes buffers from the pool until it is under its size limit. */ private synchronized void trim() { while (mCurrentSize > mSizeLimit) { byte[] buf = mBuffersByLastUse.remove(0); @@ -131,5 +127,4 @@ public class ByteArrayPool { mCurrentSize -= buf.length; } } - } diff --git a/src/main/java/com/android/volley/toolbox/ClearCacheRequest.java b/src/main/java/com/android/volley/toolbox/ClearCacheRequest.java index a3478bf..856ef80 100644 --- a/src/main/java/com/android/volley/toolbox/ClearCacheRequest.java +++ b/src/main/java/com/android/volley/toolbox/ClearCacheRequest.java @@ -16,26 +16,23 @@ package com.android.volley.toolbox; +import android.os.Handler; +import android.os.Looper; import com.android.volley.Cache; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.Response; -import android.os.Handler; -import android.os.Looper; - -/** - * A synthetic request used for clearing the cache. - */ +/** A synthetic request used for clearing the cache. */ public class ClearCacheRequest extends Request<Object> { private final Cache mCache; private final Runnable mCallback; /** * Creates a synthetic request for clearing the cache. + * * @param cache Cache to clear - * @param callback Callback to make on the main thread once the cache is clear, - * or null for none + * @param callback Callback to make on the main thread once the cache is clear, or null for none */ public ClearCacheRequest(Cache cache, Runnable callback) { super(Method.GET, null, null); @@ -65,6 +62,5 @@ public class ClearCacheRequest extends Request<Object> { } @Override - protected void deliverResponse(Object response) { - } + protected void deliverResponse(Object response) {} } diff --git a/src/main/java/com/android/volley/toolbox/DiskBasedCache.java b/src/main/java/com/android/volley/toolbox/DiskBasedCache.java index a6cd960..c49588f 100644 --- a/src/main/java/com/android/volley/toolbox/DiskBasedCache.java +++ b/src/main/java/com/android/volley/toolbox/DiskBasedCache.java @@ -17,12 +17,11 @@ package com.android.volley.toolbox; import android.os.SystemClock; +import android.support.annotation.VisibleForTesting; import android.text.TextUtils; - import com.android.volley.Cache; import com.android.volley.Header; import com.android.volley.VolleyLog; - import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; @@ -43,16 +42,15 @@ import java.util.List; import java.util.Map; /** - * Cache implementation that caches files directly onto the hard disk in the specified - * directory. The default disk usage size is 5MB, but is configurable. + * Cache implementation that caches files directly onto the hard disk in the specified directory. + * The default disk usage size is 5MB, but is configurable. * * <p>This cache supports the {@link Entry#allResponseHeaders} headers field. */ public class DiskBasedCache implements Cache { /** Map of the Key, CacheHeader pairs */ - private final Map<String, CacheHeader> mEntries = - new LinkedHashMap<String, CacheHeader>(16, .75f, true); + private final Map<String, CacheHeader> mEntries = new LinkedHashMap<>(16, .75f, true); /** Total amount of space currently used by the cache in bytes. */ private long mTotalSize = 0; @@ -74,6 +72,7 @@ public class DiskBasedCache implements Cache { /** * Constructs an instance of the DiskBasedCache at the specified directory. + * * @param rootDirectory The root directory of the cache. * @param maxCacheSizeInBytes The maximum size of the cache in bytes. */ @@ -83,17 +82,16 @@ public class DiskBasedCache implements Cache { } /** - * Constructs an instance of the DiskBasedCache at the specified directory using - * the default maximum cache size of 5MB. + * Constructs an instance of the DiskBasedCache at the specified directory using the default + * maximum cache size of 5MB. + * * @param rootDirectory The root directory of the cache. */ public DiskBasedCache(File rootDirectory) { this(rootDirectory, DEFAULT_DISK_USAGE_BYTES); } - /** - * Clears the cache. Deletes all cached files from disk. - */ + /** Clears the cache. Deletes all cached files from disk. */ @Override public synchronized void clear() { File[] files = mRootDirectory.listFiles(); @@ -107,9 +105,7 @@ public class DiskBasedCache implements Cache { VolleyLog.d("Cache cleared."); } - /** - * Returns the cache entry with the specified key if it exists, null otherwise. - */ + /** Returns the cache entry with the specified key if it exists, null otherwise. */ @Override public synchronized Entry get(String key) { CacheHeader entry = mEntries.get(key); @@ -119,14 +115,15 @@ public class DiskBasedCache implements Cache { } File file = getFileForKey(key); try { - CountingInputStream cis = new CountingInputStream( - new BufferedInputStream(createInputStream(file)), file.length()); + CountingInputStream cis = + new CountingInputStream( + new BufferedInputStream(createInputStream(file)), file.length()); try { CacheHeader entryOnDisk = CacheHeader.readHeader(cis); if (!TextUtils.equals(key, entryOnDisk.key)) { // File was shared by two keys and now holds data for a different entry! - VolleyLog.d("%s: key=%s, found=%s", - file.getAbsolutePath(), key, entryOnDisk.key); + VolleyLog.d( + "%s: key=%s, found=%s", file.getAbsolutePath(), key, entryOnDisk.key); // Remove key whose contents on disk have been replaced. removeEntry(key); return null; @@ -146,8 +143,8 @@ public class DiskBasedCache implements Cache { } /** - * Initializes the DiskBasedCache by scanning for all files currently in the - * specified root directory. Creates the root directory if necessary. + * Initializes the DiskBasedCache by scanning for all files currently in the specified root + * directory. Creates the root directory if necessary. */ @Override public synchronized void initialize() { @@ -164,8 +161,9 @@ public class DiskBasedCache implements Cache { for (File file : files) { try { long entrySize = file.length(); - CountingInputStream cis = new CountingInputStream( - new BufferedInputStream(createInputStream(file)), entrySize); + CountingInputStream cis = + new CountingInputStream( + new BufferedInputStream(createInputStream(file)), entrySize); try { CacheHeader entry = CacheHeader.readHeader(cis); // NOTE: When this entry was put, its size was recorded as data.length, but @@ -186,6 +184,7 @@ public class DiskBasedCache implements Cache { /** * Invalidates an entry in the cache. + * * @param key Cache key * @param fullExpire True to fully expire the entry, false to soft expire */ @@ -201,9 +200,7 @@ public class DiskBasedCache implements Cache { } } - /** - * Puts the entry with the specified key into the cache. - */ + /** Puts the entry with the specified key into the cache. */ @Override public synchronized void put(String key, Entry entry) { pruneIfNeeded(entry.data.length); @@ -229,21 +226,21 @@ public class DiskBasedCache implements Cache { } } - /** - * Removes the specified key from the cache if it exists. - */ + /** Removes the specified key from the cache if it exists. */ @Override public synchronized void remove(String key) { boolean deleted = getFileForKey(key).delete(); removeEntry(key); if (!deleted) { - VolleyLog.d("Could not delete cache entry for key=%s, filename=%s", + VolleyLog.d( + "Could not delete cache entry for key=%s, filename=%s", key, getFilenameForKey(key)); } } /** * Creates a pseudo-unique filename for the specified cache key. + * * @param key The key to generate a file name for. * @return A pseudo-unique filename. */ @@ -254,15 +251,14 @@ public class DiskBasedCache implements Cache { return localFilename; } - /** - * Returns a file object for the given cache key. - */ + /** Returns a file object for the given cache key. */ public File getFileForKey(String key) { return new File(mRootDirectory, getFilenameForKey(key)); } /** * Prunes the cache to fit the amount of bytes specified. + * * @param neededSpace The amount of bytes we are trying to fit into the cache. */ private void pruneIfNeeded(int neededSpace) { @@ -285,8 +281,9 @@ public class DiskBasedCache implements Cache { if (deleted) { mTotalSize -= e.size; } else { - VolleyLog.d("Could not delete cache entry for key=%s, filename=%s", - e.key, getFilenameForKey(e.key)); + VolleyLog.d( + "Could not delete cache entry for key=%s, filename=%s", + e.key, getFilenameForKey(e.key)); } iterator.remove(); prunedFiles++; @@ -297,13 +294,15 @@ public class DiskBasedCache implements Cache { } if (VolleyLog.DEBUG) { - VolleyLog.v("pruned %d files, %d bytes, %d ms", + VolleyLog.v( + "pruned %d files, %d bytes, %d ms", prunedFiles, (mTotalSize - before), SystemClock.elapsedRealtime() - startTime); } } /** * Puts the entry with the specified key into the cache. + * * @param key The key to identify the entry by. * @param entry The entry to cache. */ @@ -317,9 +316,7 @@ public class DiskBasedCache implements Cache { mEntries.put(key, entry); } - /** - * Removes the entry identified by 'key' from the cache. - */ + /** Removes the entry identified by 'key' from the cache. */ private void removeEntry(String key) { CacheHeader removed = mEntries.remove(key); if (removed != null) { @@ -329,11 +326,12 @@ public class DiskBasedCache implements Cache { /** * Reads length bytes from CountingInputStream into byte array. + * * @param cis input stream * @param length number of bytes to read * @throws IOException if fails to read all bytes */ - //VisibleForTesting + // VisibleForTesting static byte[] streamToBytes(CountingInputStream cis, long length) throws IOException { long maxLength = cis.bytesRemaining(); // Length cannot be negative or greater than bytes remaining, and must not overflow int. @@ -345,23 +343,20 @@ public class DiskBasedCache implements Cache { return bytes; } - //VisibleForTesting + // VisibleForTesting InputStream createInputStream(File file) throws FileNotFoundException { return new FileInputStream(file); } - //VisibleForTesting + // VisibleForTesting OutputStream createOutputStream(File file) throws FileNotFoundException { return new FileOutputStream(file); } - /** - * Handles holding onto the cache headers for an entry. - */ - //VisibleForTesting + /** Handles holding onto the cache headers for an entry. */ + // VisibleForTesting static class CacheHeader { - /** The size of the data identified by this CacheHeader. (This is not - * serialized to disk. */ + /** The size of the data identified by this CacheHeader. (This is not serialized to disk. */ long size; /** The key that identifies the cache entry. */ @@ -385,8 +380,14 @@ public class DiskBasedCache implements Cache { /** Headers from the response resulting in this cache entry. */ final List<Header> allResponseHeaders; - private CacheHeader(String key, String etag, long serverDate, long lastModified, long ttl, - long softTtl, List<Header> allResponseHeaders) { + private CacheHeader( + String key, + String etag, + long serverDate, + long lastModified, + long ttl, + long softTtl, + List<Header> allResponseHeaders) { this.key = key; this.etag = ("".equals(etag)) ? null : etag; this.serverDate = serverDate; @@ -398,11 +399,18 @@ public class DiskBasedCache implements Cache { /** * Instantiates a new CacheHeader object. + * * @param key The key that identifies the cache entry * @param entry The cache entry. */ CacheHeader(String key, Entry entry) { - this(key, entry.etag, entry.serverDate, entry.lastModified, entry.ttl, entry.softTtl, + this( + key, + entry.etag, + entry.serverDate, + entry.lastModified, + entry.ttl, + entry.softTtl, getAllResponseHeaders(entry)); size = entry.data.length; } @@ -419,6 +427,7 @@ public class DiskBasedCache implements Cache { /** * Reads the header from a CountingInputStream and returns a CacheHeader object. + * * @param is The InputStream to read from. * @throws IOException if fails to read header */ @@ -439,9 +448,7 @@ public class DiskBasedCache implements Cache { key, etag, serverDate, lastModified, ttl, softTtl, allResponseHeaders); } - /** - * Creates a cache entry for the specified data. - */ + /** Creates a cache entry for the specified data. */ Entry toCacheEntry(byte[] data) { Entry e = new Entry(); e.data = data; @@ -455,9 +462,7 @@ public class DiskBasedCache implements Cache { return e; } - /** - * Writes the contents of this CacheHeader to the specified OutputStream. - */ + /** Writes the contents of this CacheHeader to the specified OutputStream. */ boolean writeHeader(OutputStream os) { try { writeInt(os, CACHE_MAGIC); @@ -477,7 +482,7 @@ public class DiskBasedCache implements Cache { } } - //VisibleForTesting + @VisibleForTesting static class CountingInputStream extends FilterInputStream { private final long length; private long bytesRead; @@ -505,7 +510,7 @@ public class DiskBasedCache implements Cache { return result; } - //VisibleForTesting + @VisibleForTesting long bytesRead() { return bytesRead; } @@ -525,8 +530,8 @@ public class DiskBasedCache implements Cache { */ /** - * Simple wrapper around {@link InputStream#read()} that throws EOFException - * instead of returning -1. + * Simple wrapper around {@link InputStream#read()} that throws EOFException instead of + * returning -1. */ private static int read(InputStream is) throws IOException { int b = is.read(); @@ -553,14 +558,14 @@ public class DiskBasedCache implements Cache { } static void writeLong(OutputStream os, long n) throws IOException { - os.write((byte)(n >>> 0)); - os.write((byte)(n >>> 8)); - os.write((byte)(n >>> 16)); - os.write((byte)(n >>> 24)); - os.write((byte)(n >>> 32)); - os.write((byte)(n >>> 40)); - os.write((byte)(n >>> 48)); - os.write((byte)(n >>> 56)); + os.write((byte) (n >>> 0)); + os.write((byte) (n >>> 8)); + os.write((byte) (n >>> 16)); + os.write((byte) (n >>> 24)); + os.write((byte) (n >>> 32)); + os.write((byte) (n >>> 40)); + os.write((byte) (n >>> 48)); + os.write((byte) (n >>> 56)); } static long readLong(InputStream is) throws IOException { @@ -602,9 +607,11 @@ public class DiskBasedCache implements Cache { static List<Header> readHeaderList(CountingInputStream cis) throws IOException { int size = readInt(cis); - List<Header> result = (size == 0) - ? Collections.<Header>emptyList() - : new ArrayList<Header>(size); + if (size < 0) { + throw new IOException("readHeaderList size=" + size); + } + List<Header> result = + (size == 0) ? Collections.<Header>emptyList() : new ArrayList<Header>(); for (int i = 0; i < size; i++) { String name = readString(cis).intern(); String value = readString(cis).intern(); @@ -612,5 +619,4 @@ public class DiskBasedCache implements Cache { } return result; } - } diff --git a/src/main/java/com/android/volley/toolbox/HttpClientStack.java b/src/main/java/com/android/volley/toolbox/HttpClientStack.java index 023ee21..be0918a 100644 --- a/src/main/java/com/android/volley/toolbox/HttpClientStack.java +++ b/src/main/java/com/android/volley/toolbox/HttpClientStack.java @@ -19,7 +19,11 @@ package com.android.volley.toolbox; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Request.Method; - +import java.io.IOException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; @@ -38,23 +42,17 @@ import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; -import java.io.IOException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - /** * An HttpStack that performs request over an {@link HttpClient}. * * @deprecated The Apache HTTP library on Android is deprecated. Use {@link HurlStack} or another - * {@link BaseHttpStack} implementation. + * {@link BaseHttpStack} implementation. */ @Deprecated public class HttpClientStack implements HttpStack { protected final HttpClient mClient; - private final static String HEADER_CONTENT_TYPE = "Content-Type"; + private static final String HEADER_CONTENT_TYPE = "Content-Type"; public HttpClientStack(HttpClient client) { mClient = client; @@ -68,7 +66,7 @@ public class HttpClientStack implements HttpStack { @SuppressWarnings("unused") private static List<NameValuePair> getPostParameterPairs(Map<String, String> postParams) { - List<NameValuePair> result = new ArrayList<NameValuePair>(postParams.size()); + List<NameValuePair> result = new ArrayList<>(postParams.size()); for (String key : postParams.keySet()) { result.add(new BasicNameValuePair(key, postParams.get(key))); } @@ -91,64 +89,70 @@ public class HttpClientStack implements HttpStack { return mClient.execute(httpRequest); } - /** - * Creates the appropriate subclass of HttpUriRequest for passed in request. - */ + /** Creates the appropriate subclass of HttpUriRequest for passed in request. */ @SuppressWarnings("deprecation") - /* protected */ static HttpUriRequest createHttpRequest(Request<?> request, - Map<String, String> additionalHeaders) throws AuthFailureError { + /* protected */ static HttpUriRequest createHttpRequest( + Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError { switch (request.getMethod()) { - case Method.DEPRECATED_GET_OR_POST: { - // This is the deprecated way that needs to be handled for backwards compatibility. - // If the request's post body is null, then the assumption is that the request is - // GET. Otherwise, it is assumed that the request is a POST. - byte[] postBody = request.getPostBody(); - if (postBody != null) { - HttpPost postRequest = new HttpPost(request.getUrl()); - postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); - HttpEntity entity; - entity = new ByteArrayEntity(postBody); - postRequest.setEntity(entity); - return postRequest; - } else { - return new HttpGet(request.getUrl()); + case Method.DEPRECATED_GET_OR_POST: + { + // This is the deprecated way that needs to be handled for backwards + // compatibility. + // If the request's post body is null, then the assumption is that the request + // is + // GET. Otherwise, it is assumed that the request is a POST. + byte[] postBody = request.getPostBody(); + if (postBody != null) { + HttpPost postRequest = new HttpPost(request.getUrl()); + postRequest.addHeader( + HEADER_CONTENT_TYPE, request.getPostBodyContentType()); + HttpEntity entity; + entity = new ByteArrayEntity(postBody); + postRequest.setEntity(entity); + return postRequest; + } else { + return new HttpGet(request.getUrl()); + } } - } case Method.GET: return new HttpGet(request.getUrl()); case Method.DELETE: return new HttpDelete(request.getUrl()); - case Method.POST: { - HttpPost postRequest = new HttpPost(request.getUrl()); - postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); - setEntityIfNonEmptyBody(postRequest, request); - return postRequest; - } - case Method.PUT: { - HttpPut putRequest = new HttpPut(request.getUrl()); - putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); - setEntityIfNonEmptyBody(putRequest, request); - return putRequest; - } + case Method.POST: + { + HttpPost postRequest = new HttpPost(request.getUrl()); + postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); + setEntityIfNonEmptyBody(postRequest, request); + return postRequest; + } + case Method.PUT: + { + HttpPut putRequest = new HttpPut(request.getUrl()); + putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); + setEntityIfNonEmptyBody(putRequest, request); + return putRequest; + } case Method.HEAD: return new HttpHead(request.getUrl()); case Method.OPTIONS: return new HttpOptions(request.getUrl()); case Method.TRACE: return new HttpTrace(request.getUrl()); - case Method.PATCH: { - HttpPatch patchRequest = new HttpPatch(request.getUrl()); - patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); - setEntityIfNonEmptyBody(patchRequest, request); - return patchRequest; - } + case Method.PATCH: + { + HttpPatch patchRequest = new HttpPatch(request.getUrl()); + patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); + setEntityIfNonEmptyBody(patchRequest, request); + return patchRequest; + } default: throw new IllegalStateException("Unknown request method."); } } - private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, - Request<?> request) throws AuthFailureError { + private static void setEntityIfNonEmptyBody( + HttpEntityEnclosingRequestBase httpRequest, Request<?> request) + throws AuthFailureError { byte[] body = request.getBody(); if (body != null) { HttpEntity entity = new ByteArrayEntity(body); @@ -159,7 +163,7 @@ public class HttpClientStack implements HttpStack { /** * Called before the request is executed using the underlying HttpClient. * - * <p>Overwrite in subclasses to augment the request.</p> + * <p>Overwrite in subclasses to augment the request. */ protected void onPrepareRequest(HttpUriRequest request) throws IOException { // Nothing. @@ -170,7 +174,7 @@ public class HttpClientStack implements HttpStack { */ public static final class HttpPatch extends HttpEntityEnclosingRequestBase { - public final static String METHOD_NAME = "PATCH"; + public static final String METHOD_NAME = "PATCH"; public HttpPatch() { super(); @@ -181,9 +185,7 @@ public class HttpClientStack implements HttpStack { setURI(uri); } - /** - * @throws IllegalArgumentException if the uri is invalid. - */ + /** @throws IllegalArgumentException if the uri is invalid. */ public HttpPatch(final String uri) { super(); setURI(URI.create(uri)); @@ -193,6 +195,5 @@ public class HttpClientStack implements HttpStack { public String getMethod() { return METHOD_NAME; } - } } diff --git a/src/main/java/com/android/volley/toolbox/HttpHeaderParser.java b/src/main/java/com/android/volley/toolbox/HttpHeaderParser.java index 211c329..27d1268 100644 --- a/src/main/java/com/android/volley/toolbox/HttpHeaderParser.java +++ b/src/main/java/com/android/volley/toolbox/HttpHeaderParser.java @@ -20,7 +20,6 @@ import com.android.volley.Cache; import com.android.volley.Header; import com.android.volley.NetworkResponse; import com.android.volley.VolleyLog; - import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -31,9 +30,7 @@ import java.util.Map; import java.util.TimeZone; import java.util.TreeMap; -/** - * Utility methods for parsing HTTP headers. - */ +/** Utility methods for parsing HTTP headers. */ public class HttpHeaderParser { static final String HEADER_CONTENT_TYPE = "Content-Type"; @@ -74,7 +71,7 @@ public class HttpHeaderParser { headerValue = headers.get("Cache-Control"); if (headerValue != null) { hasCacheControl = true; - String[] tokens = headerValue.split(","); + String[] tokens = headerValue.split(",", 0); for (int i = 0; i < tokens.length; i++) { String token = tokens[i].trim(); if (token.equals("no-cache") || token.equals("no-store")) { @@ -111,9 +108,7 @@ public class HttpHeaderParser { // is more restrictive. if (hasCacheControl) { softExpire = now + maxAge * 1000; - finalExpire = mustRevalidate - ? softExpire - : softExpire + staleWhileRevalidate * 1000; + finalExpire = mustRevalidate ? softExpire : softExpire + staleWhileRevalidate * 1000; } else if (serverDate > 0 && serverExpires >= serverDate) { // Default semantic for Expire header in HTTP specification is softExpire. softExpire = now + (serverExpires - serverDate); @@ -133,9 +128,7 @@ public class HttpHeaderParser { return entry; } - /** - * Parse date in RFC1123 format, and return its value as epoch - */ + /** Parse date in RFC1123 format, and return its value as epoch */ public static long parseDateAsEpoch(String dateStr) { try { // Parse date in RFC1123 format if this header contains one @@ -153,8 +146,7 @@ public class HttpHeaderParser { } private static SimpleDateFormat newRfc1123Formatter() { - SimpleDateFormat formatter = - new SimpleDateFormat(RFC1123_FORMAT, Locale.US); + SimpleDateFormat formatter = new SimpleDateFormat(RFC1123_FORMAT, Locale.US); formatter.setTimeZone(TimeZone.getTimeZone("GMT")); return formatter; } @@ -164,15 +156,15 @@ public class HttpHeaderParser { * * @param headers An {@link java.util.Map} of headers * @param defaultCharset Charset to return if none can be found - * @return Returns the charset specified in the Content-Type of this header, - * or the defaultCharset if none can be found. + * @return Returns the charset specified in the Content-Type of this header, or the + * defaultCharset if none can be found. */ public static String parseCharset(Map<String, String> headers, String defaultCharset) { String contentType = headers.get(HEADER_CONTENT_TYPE); if (contentType != null) { - String[] params = contentType.split(";"); + String[] params = contentType.split(";", 0); for (int i = 1; i < params.length; i++) { - String[] pair = params[i].trim().split("="); + String[] pair = params[i].trim().split("=", 0); if (pair.length == 2) { if (pair[0].equals("charset")) { return pair[1]; @@ -185,8 +177,8 @@ public class HttpHeaderParser { } /** - * Returns the charset specified in the Content-Type of this header, - * or the HTTP default (ISO-8859-1) if none can be found. + * Returns the charset specified in the Content-Type of this header, or the HTTP default + * (ISO-8859-1) if none can be found. */ public static String parseCharset(Map<String, String> headers) { return parseCharset(headers, DEFAULT_CONTENT_CHARSET); diff --git a/src/main/java/com/android/volley/toolbox/HttpResponse.java b/src/main/java/com/android/volley/toolbox/HttpResponse.java index db719bc..9a9294f 100644 --- a/src/main/java/com/android/volley/toolbox/HttpResponse.java +++ b/src/main/java/com/android/volley/toolbox/HttpResponse.java @@ -16,7 +16,6 @@ package com.android.volley.toolbox; import com.android.volley.Header; - import java.io.InputStream; import java.util.Collections; import java.util.List; @@ -36,7 +35,7 @@ public final class HttpResponse { * @param headers the response headers */ public HttpResponse(int statusCode, List<Header> headers) { - this(statusCode, headers, -1 /* contentLength */, null /* content */); + this(statusCode, headers, /* contentLength= */ -1, /* content= */ null); } /** diff --git a/src/main/java/com/android/volley/toolbox/HttpStack.java b/src/main/java/com/android/volley/toolbox/HttpStack.java index 5d34b44..85179a7 100644 --- a/src/main/java/com/android/volley/toolbox/HttpStack.java +++ b/src/main/java/com/android/volley/toolbox/HttpStack.java @@ -18,11 +18,9 @@ package com.android.volley.toolbox; import com.android.volley.AuthFailureError; import com.android.volley.Request; - -import org.apache.http.HttpResponse; - import java.io.IOException; import java.util.Map; +import org.apache.http.HttpResponse; /** * An HTTP stack abstraction. @@ -37,14 +35,13 @@ public interface HttpStack { * Performs an HTTP request with the given parameters. * * <p>A GET request is sent if request.getPostBody() == null. A POST request is sent otherwise, - * and the Content-Type header is set to request.getPostBodyContentType().</p> + * and the Content-Type header is set to request.getPostBodyContentType(). * * @param request the request to perform - * @param additionalHeaders additional headers to be sent together with - * {@link Request#getHeaders()} + * @param additionalHeaders additional headers to be sent together with {@link + * Request#getHeaders()} * @return the HTTP response */ HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) - throws IOException, AuthFailureError; - + throws IOException, AuthFailureError; } diff --git a/src/main/java/com/android/volley/toolbox/HurlStack.java b/src/main/java/com/android/volley/toolbox/HurlStack.java index a975a71..dd73759 100644 --- a/src/main/java/com/android/volley/toolbox/HurlStack.java +++ b/src/main/java/com/android/volley/toolbox/HurlStack.java @@ -16,12 +16,13 @@ package com.android.volley.toolbox; +import android.support.annotation.VisibleForTesting; import com.android.volley.AuthFailureError; import com.android.volley.Header; import com.android.volley.Request; import com.android.volley.Request.Method; - import java.io.DataOutputStream; +import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; @@ -30,24 +31,19 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSocketFactory; -/** - * An {@link HttpStack} based on {@link HttpURLConnection}. - */ +/** A {@link BaseHttpStack} based on {@link HttpURLConnection}. */ public class HurlStack extends BaseHttpStack { private static final int HTTP_CONTINUE = 100; - /** - * An interface for transforming URLs before use. - */ + /** An interface for transforming URLs before use. */ public interface UrlRewriter { /** - * Returns a URL to use instead of the provided one, or null to indicate - * this URL should not be used at all. + * Returns a URL to use instead of the provided one, or null to indicate this URL should not + * be used at all. */ String rewriteUrl(String originalUrl); } @@ -56,14 +52,12 @@ public class HurlStack extends BaseHttpStack { private final SSLSocketFactory mSslSocketFactory; public HurlStack() { - this(null); + this(/* urlRewriter = */ null); } - /** - * @param urlRewriter Rewriter to use for request URLs - */ + /** @param urlRewriter Rewriter to use for request URLs */ public HurlStack(UrlRewriter urlRewriter) { - this(urlRewriter, null); + this(urlRewriter, /* sslSocketFactory = */ null); } /** @@ -91,27 +85,40 @@ public class HurlStack extends BaseHttpStack { } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); - for (String headerName : map.keySet()) { - connection.addRequestProperty(headerName, map.get(headerName)); - } - setConnectionParametersForRequest(connection, request); - // Initialize HttpResponse with data from the HttpURLConnection. - int responseCode = connection.getResponseCode(); - if (responseCode == -1) { - // -1 is returned by getResponseCode() if the response code could not be retrieved. - // Signal to the caller that something was wrong with the connection. - throw new IOException("Could not retrieve response code from HttpUrlConnection."); - } + boolean keepConnectionOpen = false; + try { + for (String headerName : map.keySet()) { + connection.addRequestProperty(headerName, map.get(headerName)); + } + setConnectionParametersForRequest(connection, request); + // Initialize HttpResponse with data from the HttpURLConnection. + int responseCode = connection.getResponseCode(); + if (responseCode == -1) { + // -1 is returned by getResponseCode() if the response code could not be retrieved. + // Signal to the caller that something was wrong with the connection. + throw new IOException("Could not retrieve response code from HttpUrlConnection."); + } - if (!hasResponseBody(request.getMethod(), responseCode)) { - return new HttpResponse(responseCode, convertHeaders(connection.getHeaderFields())); - } + if (!hasResponseBody(request.getMethod(), responseCode)) { + return new HttpResponse(responseCode, convertHeaders(connection.getHeaderFields())); + } - return new HttpResponse(responseCode, convertHeaders(connection.getHeaderFields()), - connection.getContentLength(), inputStreamFromConnection(connection)); + // Need to keep the connection open until the stream is consumed by the caller. Wrap the + // stream such that close() will disconnect the connection. + keepConnectionOpen = true; + return new HttpResponse( + responseCode, + convertHeaders(connection.getHeaderFields()), + connection.getContentLength(), + new UrlConnectionInputStream(connection)); + } finally { + if (!keepConnectionOpen) { + connection.disconnect(); + } + } } - // VisibleForTesting + @VisibleForTesting static List<Header> convertHeaders(Map<String, List<String>> responseHeaders) { List<Header> headerList = new ArrayList<>(responseHeaders.size()); for (Map.Entry<String, List<String>> entry : responseHeaders.entrySet()) { @@ -128,6 +135,7 @@ public class HurlStack extends BaseHttpStack { /** * Checks if a response message contains a body. + * * @see <a href="https://tools.ietf.org/html/rfc7230#section-3.3">RFC 7230 section 3.3</a> * @param requestMethod request method * @param responseCode response status code @@ -135,13 +143,33 @@ public class HurlStack extends BaseHttpStack { */ private static boolean hasResponseBody(int requestMethod, int responseCode) { return requestMethod != Request.Method.HEAD - && !(HTTP_CONTINUE <= responseCode && responseCode < HttpURLConnection.HTTP_OK) - && responseCode != HttpURLConnection.HTTP_NO_CONTENT - && responseCode != HttpURLConnection.HTTP_NOT_MODIFIED; + && !(HTTP_CONTINUE <= responseCode && responseCode < HttpURLConnection.HTTP_OK) + && responseCode != HttpURLConnection.HTTP_NO_CONTENT + && responseCode != HttpURLConnection.HTTP_NOT_MODIFIED; + } + + /** + * Wrapper for a {@link HttpURLConnection}'s InputStream which disconnects the connection on + * stream close. + */ + static class UrlConnectionInputStream extends FilterInputStream { + private final HttpURLConnection mConnection; + + UrlConnectionInputStream(HttpURLConnection connection) { + super(inputStreamFromConnection(connection)); + mConnection = connection; + } + + @Override + public void close() throws IOException { + super.close(); + mConnection.disconnect(); + } } /** * Initializes an {@link InputStream} from the given {@link HttpURLConnection}. + * * @param connection * @return an HttpEntity populated with data from <code>connection</code>. */ @@ -155,9 +183,7 @@ public class HurlStack extends BaseHttpStack { return inputStream; } - /** - * Create an {@link HttpURLConnection} for the specified {@code url}. - */ + /** Create an {@link HttpURLConnection} for the specified {@code url}. */ protected HttpURLConnection createConnection(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); @@ -171,6 +197,7 @@ public class HurlStack extends BaseHttpStack { /** * Opens an {@link HttpURLConnection} with parameters. + * * @param url * @return an open connection * @throws IOException @@ -186,15 +213,15 @@ public class HurlStack extends BaseHttpStack { // use caller-provided custom SslSocketFactory, if any, for HTTPS if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { - ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory); + ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory); } return connection; } @SuppressWarnings("deprecation") - /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, - Request<?> request) throws IOException, AuthFailureError { + /* package */ static void setConnectionParametersForRequest( + HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards compatibility. diff --git a/src/main/java/com/android/volley/toolbox/ImageLoader.java b/src/main/java/com/android/volley/toolbox/ImageLoader.java index 33a119b..076c212 100644 --- a/src/main/java/com/android/volley/toolbox/ImageLoader.java +++ b/src/main/java/com/android/volley/toolbox/ImageLoader.java @@ -1,16 +1,14 @@ -/** +/* * Copyright (C) 2013 The Android Open Source Project * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.android.volley.toolbox; @@ -19,25 +17,27 @@ import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.os.Handler; import android.os.Looper; +import android.support.annotation.MainThread; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; +import com.android.volley.ResponseDelivery; import com.android.volley.VolleyError; - +import java.util.ArrayList; import java.util.HashMap; -import java.util.LinkedList; +import java.util.List; /** * Helper that handles loading and caching images from remote URLs. * - * The simple way to use this class is to call {@link ImageLoader#get(String, ImageListener)} - * and to pass in the default image listener provided by - * {@link ImageLoader#getImageListener(ImageView, int, int)}. Note that all function calls to - * this class must be made from the main thead, and all responses will be delivered to the main - * thread as well. + * <p>The simple way to use this class is to call {@link ImageLoader#get(String, ImageListener)} and + * to pass in the default image listener provided by {@link ImageLoader#getImageListener(ImageView, + * int, int)}. Note that all function calls to this class must be made from the main thread, and all + * responses will be delivered to the main thread as well. Custom {@link ResponseDelivery}s which + * don't use the main thread are not supported. */ public class ImageLoader { /** RequestQueue for dispatching ImageRequests onto. */ @@ -50,15 +50,13 @@ public class ImageLoader { private final ImageCache mCache; /** - * HashMap of Cache keys -> BatchedImageRequest used to track in-flight requests so - * that we can coalesce multiple requests to the same URL into a single network request. + * HashMap of Cache keys -> BatchedImageRequest used to track in-flight requests so that we can + * coalesce multiple requests to the same URL into a single network request. */ - private final HashMap<String, BatchedImageRequest> mInFlightRequests = - new HashMap<String, BatchedImageRequest>(); + private final HashMap<String, BatchedImageRequest> mInFlightRequests = new HashMap<>(); /** HashMap of the currently pending responses (waiting to be delivered). */ - private final HashMap<String, BatchedImageRequest> mBatchedResponses = - new HashMap<String, BatchedImageRequest>(); + private final HashMap<String, BatchedImageRequest> mBatchedResponses = new HashMap<>(); /** Handler to the main thread. */ private final Handler mHandler = new Handler(Looper.getMainLooper()); @@ -67,17 +65,19 @@ public class ImageLoader { private Runnable mRunnable; /** - * Simple cache adapter interface. If provided to the ImageLoader, it - * will be used as an L1 cache before dispatch to Volley. Implementations - * must not block. Implementation with an LruCache is recommended. + * Simple cache adapter interface. If provided to the ImageLoader, it will be used as an L1 + * cache before dispatch to Volley. Implementations must not block. Implementation with an + * LruCache is recommended. */ public interface ImageCache { Bitmap getBitmap(String url); + void putBitmap(String url, Bitmap bitmap); } /** * Constructs a new ImageLoader. + * * @param queue The RequestQueue to use for making image requests. * @param imageCache The cache to use as an L1 cache. */ @@ -87,15 +87,16 @@ public class ImageLoader { } /** - * The default implementation of ImageListener which handles basic functionality - * of showing a default image until the network response is received, at which point - * it will switch to either the actual image or the error image. + * The default implementation of ImageListener which handles basic functionality of showing a + * default image until the network response is received, at which point it will switch to either + * the actual image or the error image. + * * @param view The imageView that the listener is associated with. * @param defaultImageResId Default image resource ID to use, or 0 if it doesn't exist. * @param errorImageResId Error image resource ID to use, or 0 if it doesn't exist. */ - public static ImageListener getImageListener(final ImageView view, - final int defaultImageResId, final int errorImageResId) { + public static ImageListener getImageListener( + final ImageView view, final int defaultImageResId, final int errorImageResId) { return new ImageListener() { @Override public void onErrorResponse(VolleyError error) { @@ -118,32 +119,30 @@ public class ImageLoader { /** * Interface for the response handlers on image requests. * - * The call flow is this: - * 1. Upon being attached to a request, onResponse(response, true) will - * be invoked to reflect any cached data that was already available. If the - * data was available, response.getBitmap() will be non-null. + * <p>The call flow is this: 1. Upon being attached to a request, onResponse(response, true) + * will be invoked to reflect any cached data that was already available. If the data was + * available, response.getBitmap() will be non-null. * - * 2. After a network response returns, only one of the following cases will happen: - * - onResponse(response, false) will be called if the image was loaded. - * or - * - onErrorResponse will be called if there was an error loading the image. + * <p>2. After a network response returns, only one of the following cases will happen: - + * onResponse(response, false) will be called if the image was loaded. or - onErrorResponse will + * be called if there was an error loading the image. */ public interface ImageListener extends ErrorListener { /** * Listens for non-error changes to the loading of the image request. * - * @param response Holds all information pertaining to the request, as well - * as the bitmap (if it is loaded). - * @param isImmediate True if this was called during ImageLoader.get() variants. - * This can be used to differentiate between a cached image loading and a network - * image loading in order to, for example, run an animation to fade in network loaded - * images. + * @param response Holds all information pertaining to the request, as well as the bitmap + * (if it is loaded). + * @param isImmediate True if this was called during ImageLoader.get() variants. This can be + * used to differentiate between a cached image loading and a network image loading in + * order to, for example, run an animation to fade in network loaded images. */ void onResponse(ImageContainer response, boolean isImmediate); } /** * Checks if the item is available in the cache. + * * @param requestUrl The url of the remote image * @param maxWidth The maximum width of the returned image. * @param maxHeight The maximum height of the returned image. @@ -156,14 +155,17 @@ public class ImageLoader { /** * Checks if the item is available in the cache. * + * <p>Must be called from the main thread. + * * @param requestUrl The url of the remote image - * @param maxWidth The maximum width of the returned image. - * @param maxHeight The maximum height of the returned image. - * @param scaleType The scaleType of the imageView. + * @param maxWidth The maximum width of the returned image. + * @param maxHeight The maximum height of the returned image. + * @param scaleType The scaleType of the imageView. * @return True if the item exists in cache, false otherwise. */ + @MainThread public boolean isCached(String requestUrl, int maxWidth, int maxHeight, ScaleType scaleType) { - throwIfNotOnMainThread(); + Threads.throwIfNotOnMainThread(); String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType); return mCache.getBitmap(cacheKey) != null; @@ -172,43 +174,50 @@ public class ImageLoader { /** * Returns an ImageContainer for the requested URL. * - * The ImageContainer will contain either the specified default bitmap or the loaded bitmap. - * If the default was returned, the {@link ImageLoader} will be invoked when the - * request is fulfilled. + * <p>The ImageContainer will contain either the specified default bitmap or the loaded bitmap. + * If the default was returned, the {@link ImageLoader} will be invoked when the request is + * fulfilled. * * @param requestUrl The URL of the image to be loaded. */ public ImageContainer get(String requestUrl, final ImageListener listener) { - return get(requestUrl, listener, 0, 0); + return get(requestUrl, listener, /* maxWidth= */ 0, /* maxHeight= */ 0); } /** - * Equivalent to calling {@link #get(String, ImageListener, int, int, ScaleType)} with - * {@code Scaletype == ScaleType.CENTER_INSIDE}. + * Equivalent to calling {@link #get(String, ImageListener, int, int, ScaleType)} with {@code + * Scaletype == ScaleType.CENTER_INSIDE}. */ - public ImageContainer get(String requestUrl, ImageListener imageListener, - int maxWidth, int maxHeight) { + public ImageContainer get( + String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight) { return get(requestUrl, imageListener, maxWidth, maxHeight, ScaleType.CENTER_INSIDE); } /** - * Issues a bitmap request with the given URL if that image is not available - * in the cache, and returns a bitmap container that contains all of the data - * relating to the request (as well as the default image if the requested - * image is not available). + * Issues a bitmap request with the given URL if that image is not available in the cache, and + * returns a bitmap container that contains all of the data relating to the request (as well as + * the default image if the requested image is not available). + * + * <p>Must be called from the main thread. + * * @param requestUrl The url of the remote image * @param imageListener The listener to call when the remote image is loaded * @param maxWidth The maximum width of the returned image. * @param maxHeight The maximum height of the returned image. * @param scaleType The ImageViews ScaleType used to calculate the needed image size. - * @return A container object that contains all of the properties of the request, as well as - * the currently available image (default if remote is not loaded). + * @return A container object that contains all of the properties of the request, as well as the + * currently available image (default if remote is not loaded). */ - public ImageContainer get(String requestUrl, ImageListener imageListener, - int maxWidth, int maxHeight, ScaleType scaleType) { + @MainThread + public ImageContainer get( + String requestUrl, + ImageListener imageListener, + int maxWidth, + int maxHeight, + ScaleType scaleType) { // only fulfill requests that were initiated from the main thread. - throwIfNotOnMainThread(); + Threads.throwIfNotOnMainThread(); final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType); @@ -216,7 +225,9 @@ public class ImageLoader { Bitmap cachedBitmap = mCache.getBitmap(cacheKey); if (cachedBitmap != null) { // Return the cached bitmap. - ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null); + ImageContainer container = + new ImageContainer( + cachedBitmap, requestUrl, /* cacheKey= */ null, /* listener= */ null); imageListener.onResponse(container, true); return container; } @@ -238,33 +249,44 @@ public class ImageLoader { // The request is not already in flight. Send the new request to the network and // track it. - Request<Bitmap> newRequest = makeImageRequest(requestUrl, maxWidth, maxHeight, scaleType, - cacheKey); + Request<Bitmap> newRequest = + makeImageRequest(requestUrl, maxWidth, maxHeight, scaleType, cacheKey); mRequestQueue.add(newRequest); - mInFlightRequests.put(cacheKey, - new BatchedImageRequest(newRequest, imageContainer)); + mInFlightRequests.put(cacheKey, new BatchedImageRequest(newRequest, imageContainer)); return imageContainer; } - protected Request<Bitmap> makeImageRequest(String requestUrl, int maxWidth, int maxHeight, - ScaleType scaleType, final String cacheKey) { - return new ImageRequest(requestUrl, new Listener<Bitmap>() { - @Override - public void onResponse(Bitmap response) { - onGetImageSuccess(cacheKey, response); - } - }, maxWidth, maxHeight, scaleType, Config.RGB_565, new ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - onGetImageError(cacheKey, error); - } - }); + protected Request<Bitmap> makeImageRequest( + String requestUrl, + int maxWidth, + int maxHeight, + ScaleType scaleType, + final String cacheKey) { + return new ImageRequest( + requestUrl, + new Listener<Bitmap>() { + @Override + public void onResponse(Bitmap response) { + onGetImageSuccess(cacheKey, response); + } + }, + maxWidth, + maxHeight, + scaleType, + Config.RGB_565, + new ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + onGetImageError(cacheKey, error); + } + }); } /** * Sets the amount of time to wait after the first response arrives before delivering all * responses. Batching can be disabled entirely by passing in 0. + * * @param newBatchedResponseDelayMs The time in milliseconds to wait. */ public void setBatchedResponseDelay(int newBatchedResponseDelayMs) { @@ -273,6 +295,7 @@ public class ImageLoader { /** * Handler for when an image was successfully loaded. + * * @param cacheKey The cache key that is associated with the image request. * @param response The bitmap that was returned from the network. */ @@ -294,6 +317,7 @@ public class ImageLoader { /** * Handler for when an image failed to load. + * * @param cacheKey The cache key that is associated with the image request. */ protected void onGetImageError(String cacheKey, VolleyError error) { @@ -310,13 +334,11 @@ public class ImageLoader { } } - /** - * Container object for all of the data surrounding an image request. - */ + /** Container object for all of the data surrounding an image request. */ public class ImageContainer { /** - * The most relevant bitmap for the container. If the image was in cache, the - * Holder to use for the final bitmap (the one that pairs to the requested URL). + * The most relevant bitmap for the container. If the image was in cache, the Holder to use + * for the final bitmap (the one that pairs to the requested URL). */ private Bitmap mBitmap; @@ -330,12 +352,13 @@ public class ImageLoader { /** * Constructs a BitmapContainer object. + * * @param bitmap The final bitmap (if it exists). * @param requestUrl The requested URL for this container. * @param cacheKey The cache key that identifies the requested URL for this container. */ - public ImageContainer(Bitmap bitmap, String requestUrl, - String cacheKey, ImageListener listener) { + public ImageContainer( + Bitmap bitmap, String requestUrl, String cacheKey, ImageListener listener) { mBitmap = bitmap; mRequestUrl = requestUrl; mCacheKey = cacheKey; @@ -344,8 +367,13 @@ public class ImageLoader { /** * Releases interest in the in-flight request (and cancels it if no one else is listening). + * + * <p>Must be called from the main thread. */ + @MainThread public void cancelRequest() { + Threads.throwIfNotOnMainThread(); + if (mListener == null) { return; } @@ -375,9 +403,7 @@ public class ImageLoader { return mBitmap; } - /** - * Returns the requested URL for this container. - */ + /** Returns the requested URL for this container. */ public String getRequestUrl() { return mRequestUrl; } @@ -387,7 +413,7 @@ public class ImageLoader { * Wrapper class used to map a Request to the set of active ImageContainer objects that are * interested in its results. */ - private class BatchedImageRequest { + private static class BatchedImageRequest { /** The request being tracked */ private final Request<?> mRequest; @@ -398,10 +424,11 @@ public class ImageLoader { private VolleyError mError; /** List of all of the active ImageContainers that are interested in the request */ - private final LinkedList<ImageContainer> mContainers = new LinkedList<ImageContainer>(); + private final List<ImageContainer> mContainers = new ArrayList<>(); /** * Constructs a new BatchedImageRequest object + * * @param request The request being tracked * @param container The ImageContainer of the person who initiated the request. */ @@ -410,31 +437,28 @@ public class ImageLoader { mContainers.add(container); } - /** - * Set the error for this response - */ + /** Set the error for this response */ public void setError(VolleyError error) { mError = error; } - /** - * Get the error for this response - */ + /** Get the error for this response */ public VolleyError getError() { return mError; } /** - * Adds another ImageContainer to the list of those interested in the results of - * the request. + * Adds another ImageContainer to the list of those interested in the results of the + * request. */ public void addContainer(ImageContainer container) { mContainers.add(container); } /** - * Detatches the bitmap container from the request and cancels the request if no one is - * left listening. + * Detaches the bitmap container from the request and cancels the request if no one is left + * listening. + * * @param container The container to remove from the list * @return True if the request was canceled, false otherwise. */ @@ -450,6 +474,7 @@ public class ImageLoader { /** * Starts the runnable for batched delivery of responses if it is not already started. + * * @param cacheKey The cacheKey of the response being delivered. * @param request The BatchedImageRequest to be delivered. */ @@ -458,50 +483,54 @@ public class ImageLoader { // If we don't already have a batch delivery runnable in flight, make a new one. // Note that this will be used to deliver responses to all callers in mBatchedResponses. if (mRunnable == null) { - mRunnable = new Runnable() { - @Override - public void run() { - for (BatchedImageRequest bir : mBatchedResponses.values()) { - for (ImageContainer container : bir.mContainers) { - // If one of the callers in the batched request canceled the request - // after the response was received but before it was delivered, - // skip them. - if (container.mListener == null) { - continue; - } - if (bir.getError() == null) { - container.mBitmap = bir.mResponseBitmap; - container.mListener.onResponse(container, false); - } else { - container.mListener.onErrorResponse(bir.getError()); + mRunnable = + new Runnable() { + @Override + public void run() { + for (BatchedImageRequest bir : mBatchedResponses.values()) { + for (ImageContainer container : bir.mContainers) { + // If one of the callers in the batched request canceled the + // request + // after the response was received but before it was delivered, + // skip them. + if (container.mListener == null) { + continue; + } + if (bir.getError() == null) { + container.mBitmap = bir.mResponseBitmap; + container.mListener.onResponse(container, false); + } else { + container.mListener.onErrorResponse(bir.getError()); + } + } } + mBatchedResponses.clear(); + mRunnable = null; } - } - mBatchedResponses.clear(); - mRunnable = null; - } - - }; + }; // Post the runnable. mHandler.postDelayed(mRunnable, mBatchResponseDelayMs); } } - private void throwIfNotOnMainThread() { - if (Looper.myLooper() != Looper.getMainLooper()) { - throw new IllegalStateException("ImageLoader must be invoked from the main thread."); - } - } /** * Creates a cache key for use with the L1 cache. + * * @param url The URL of the request. * @param maxWidth The max-width of the output. * @param maxHeight The max-height of the output. * @param scaleType The scaleType of the imageView. */ - private static String getCacheKey(String url, int maxWidth, int maxHeight, ScaleType scaleType) { - return new StringBuilder(url.length() + 12).append("#W").append(maxWidth) - .append("#H").append(maxHeight).append("#S").append(scaleType.ordinal()).append(url) + private static String getCacheKey( + String url, int maxWidth, int maxHeight, ScaleType scaleType) { + return new StringBuilder(url.length() + 12) + .append("#W") + .append(maxWidth) + .append("#H") + .append(maxHeight) + .append("#S") + .append(scaleType.ordinal()) + .append(url) .toString(); } } diff --git a/src/main/java/com/android/volley/toolbox/ImageRequest.java b/src/main/java/com/android/volley/toolbox/ImageRequest.java index 1db7e35..c804267 100644 --- a/src/main/java/com/android/volley/toolbox/ImageRequest.java +++ b/src/main/java/com/android/volley/toolbox/ImageRequest.java @@ -19,8 +19,9 @@ package com.android.volley.toolbox; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; +import android.support.annotation.GuardedBy; +import android.support.annotation.VisibleForTesting; import android.widget.ImageView.ScaleType; - import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; @@ -28,10 +29,7 @@ import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyLog; -/** - * A canned request for getting an image at a given URL and calling - * back with a decoded Bitmap. - */ +/** A canned request for getting an image at a given URL and calling back with a decoded Bitmap. */ public class ImageRequest extends Request<Bitmap> { /** Socket timeout in milliseconds for image requests */ public static final int DEFAULT_IMAGE_TIMEOUT_MS = 1000; @@ -45,8 +43,9 @@ public class ImageRequest extends Request<Bitmap> { /** Lock to guard mListener as it is cleared on cancel() and read on delivery. */ private final Object mLock = new Object(); - // @GuardedBy("mLock") + @GuardedBy("mLock") private Response.Listener<Bitmap> mListener; + private final Config mDecodeConfig; private final int mMaxWidth; private final int mMaxHeight; @@ -56,28 +55,34 @@ public class ImageRequest extends Request<Bitmap> { private static final Object sDecodeLock = new Object(); /** - * Creates a new image request, decoding to a maximum specified width and - * height. If both width and height are zero, the image will be decoded to - * its natural size. If one of the two is nonzero, that dimension will be - * clamped and the other one will be set to preserve the image's aspect - * ratio. If both width and height are nonzero, the image will be decoded to - * be fit in the rectangle of dimensions width x height while keeping its - * aspect ratio. + * Creates a new image request, decoding to a maximum specified width and height. If both width + * and height are zero, the image will be decoded to its natural size. If one of the two is + * nonzero, that dimension will be clamped and the other one will be set to preserve the image's + * aspect ratio. If both width and height are nonzero, the image will be decoded to be fit in + * the rectangle of dimensions width x height while keeping its aspect ratio. * * @param url URL of the image * @param listener Listener to receive the decoded bitmap * @param maxWidth Maximum width to decode this bitmap to, or zero for none - * @param maxHeight Maximum height to decode this bitmap to, or zero for - * none + * @param maxHeight Maximum height to decode this bitmap to, or zero for none * @param scaleType The ImageViews ScaleType used to calculate the needed image size. * @param decodeConfig Format to decode the bitmap to * @param errorListener Error listener, or null to ignore errors */ - public ImageRequest(String url, Response.Listener<Bitmap> listener, int maxWidth, int maxHeight, - ScaleType scaleType, Config decodeConfig, Response.ErrorListener errorListener) { + public ImageRequest( + String url, + Response.Listener<Bitmap> listener, + int maxWidth, + int maxHeight, + ScaleType scaleType, + Config decodeConfig, + Response.ErrorListener errorListener) { super(Method.GET, url, errorListener); - setRetryPolicy(new DefaultRetryPolicy(DEFAULT_IMAGE_TIMEOUT_MS, DEFAULT_IMAGE_MAX_RETRIES, - DEFAULT_IMAGE_BACKOFF_MULT)); + setRetryPolicy( + new DefaultRetryPolicy( + DEFAULT_IMAGE_TIMEOUT_MS, + DEFAULT_IMAGE_MAX_RETRIES, + DEFAULT_IMAGE_BACKOFF_MULT)); mListener = listener; mDecodeConfig = decodeConfig; mMaxWidth = maxWidth; @@ -86,15 +91,27 @@ public class ImageRequest extends Request<Bitmap> { } /** - * For API compatibility with the pre-ScaleType variant of the constructor. Equivalent to - * the normal constructor with {@code ScaleType.CENTER_INSIDE}. + * For API compatibility with the pre-ScaleType variant of the constructor. Equivalent to the + * normal constructor with {@code ScaleType.CENTER_INSIDE}. */ @Deprecated - public ImageRequest(String url, Response.Listener<Bitmap> listener, int maxWidth, int maxHeight, - Config decodeConfig, Response.ErrorListener errorListener) { - this(url, listener, maxWidth, maxHeight, - ScaleType.CENTER_INSIDE, decodeConfig, errorListener); + public ImageRequest( + String url, + Response.Listener<Bitmap> listener, + int maxWidth, + int maxHeight, + Config decodeConfig, + Response.ErrorListener errorListener) { + this( + url, + listener, + maxWidth, + maxHeight, + ScaleType.CENTER_INSIDE, + decodeConfig, + errorListener); } + @Override public Priority getPriority() { return Priority.LOW; @@ -103,17 +120,20 @@ public class ImageRequest extends Request<Bitmap> { /** * Scales one side of a rectangle to fit aspect ratio. * - * @param maxPrimary Maximum size of the primary dimension (i.e. width for - * max width), or zero to maintain aspect ratio with secondary - * dimension - * @param maxSecondary Maximum size of the secondary dimension, or zero to - * maintain aspect ratio with primary dimension + * @param maxPrimary Maximum size of the primary dimension (i.e. width for max width), or zero + * to maintain aspect ratio with secondary dimension + * @param maxSecondary Maximum size of the secondary dimension, or zero to maintain aspect ratio + * with primary dimension * @param actualPrimary Actual size of the primary dimension * @param actualSecondary Actual size of the secondary dimension * @param scaleType The ScaleType used to calculate the needed image size. */ - private static int getResizedDimension(int maxPrimary, int maxSecondary, int actualPrimary, - int actualSecondary, ScaleType scaleType) { + private static int getResizedDimension( + int maxPrimary, + int maxSecondary, + int actualPrimary, + int actualSecondary, + ScaleType scaleType) { // If no dominant value at all, just return the actual. if ((maxPrimary == 0) && (maxSecondary == 0)) { @@ -168,9 +188,7 @@ public class ImageRequest extends Request<Bitmap> { } } - /** - * The real guts of parseNetworkResponse. Broken out for readability. - */ + /** The real guts of parseNetworkResponse. Broken out for readability. */ private Response<Bitmap> doParse(NetworkResponse response) { byte[] data = response.data; BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); @@ -186,25 +204,26 @@ public class ImageRequest extends Request<Bitmap> { int actualHeight = decodeOptions.outHeight; // Then compute the dimensions we would ideally like to decode to. - int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight, - actualWidth, actualHeight, mScaleType); - int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth, - actualHeight, actualWidth, mScaleType); + int desiredWidth = + getResizedDimension( + mMaxWidth, mMaxHeight, actualWidth, actualHeight, mScaleType); + int desiredHeight = + getResizedDimension( + mMaxHeight, mMaxWidth, actualHeight, actualWidth, mScaleType); // Decode to the nearest power of two scaling factor. decodeOptions.inJustDecodeBounds = false; // TODO(ficus): Do we need this or is it okay since API 8 doesn't support it? // decodeOptions.inPreferQualityOverSpeed = PREFER_QUALITY_OVER_SPEED; decodeOptions.inSampleSize = - findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight); - Bitmap tempBitmap = - BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); + findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight); + Bitmap tempBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); // If necessary, scale down to the maximal acceptable size. - if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth || - tempBitmap.getHeight() > desiredHeight)) { - bitmap = Bitmap.createScaledBitmap(tempBitmap, - desiredWidth, desiredHeight, true); + if (tempBitmap != null + && (tempBitmap.getWidth() > desiredWidth + || tempBitmap.getHeight() > desiredHeight)) { + bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true); tempBitmap.recycle(); } else { bitmap = tempBitmap; @@ -238,15 +257,15 @@ public class ImageRequest extends Request<Bitmap> { } /** - * Returns the largest power-of-two divisor for use in downscaling a bitmap - * that will not result in the scaling past the desired dimensions. + * Returns the largest power-of-two divisor for use in downscaling a bitmap that will not result + * in the scaling past the desired dimensions. * * @param actualWidth Actual width of the bitmap * @param actualHeight Actual height of the bitmap * @param desiredWidth Desired width of the bitmap * @param desiredHeight Desired height of the bitmap */ - // Visible for testing. + @VisibleForTesting static int findBestSampleSize( int actualWidth, int actualHeight, int desiredWidth, int desiredHeight) { double wr = (double) actualWidth / desiredWidth; diff --git a/src/main/java/com/android/volley/toolbox/JsonArrayRequest.java b/src/main/java/com/android/volley/toolbox/JsonArrayRequest.java index ba35d26..757c7f9 100644 --- a/src/main/java/com/android/volley/toolbox/JsonArrayRequest.java +++ b/src/main/java/com/android/volley/toolbox/JsonArrayRequest.java @@ -21,19 +21,16 @@ import com.android.volley.ParseError; import com.android.volley.Response; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; - +import java.io.UnsupportedEncodingException; import org.json.JSONArray; import org.json.JSONException; -import java.io.UnsupportedEncodingException; - -/** - * A request for retrieving a {@link JSONArray} response body at a given URL. - */ +/** A request for retrieving a {@link JSONArray} response body at a given URL. */ public class JsonArrayRequest extends JsonRequest<JSONArray> { /** * Creates a new request. + * * @param url URL to fetch the JSON from * @param listener Listener to receive the JSON response * @param errorListener Error listener, or null to ignore errors. @@ -44,26 +41,37 @@ public class JsonArrayRequest extends JsonRequest<JSONArray> { /** * Creates a new request. + * * @param method the HTTP method to use * @param url URL to fetch the JSON from * @param jsonRequest A {@link JSONArray} to post with the request. Null is allowed and - * indicates no parameters will be posted along with request. + * indicates no parameters will be posted along with request. * @param listener Listener to receive the JSON response * @param errorListener Error listener, or null to ignore errors. */ - public JsonArrayRequest(int method, String url, JSONArray jsonRequest, - Listener<JSONArray> listener, ErrorListener errorListener) { - super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, + public JsonArrayRequest( + int method, + String url, + JSONArray jsonRequest, + Listener<JSONArray> listener, + ErrorListener errorListener) { + super( + method, + url, + (jsonRequest == null) ? null : jsonRequest.toString(), + listener, errorListener); } @Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { try { - String jsonString = new String(response.data, - HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET)); - return Response.success(new JSONArray(jsonString), - HttpHeaderParser.parseCacheHeaders(response)); + String jsonString = + new String( + response.data, + HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET)); + return Response.success( + new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { diff --git a/src/main/java/com/android/volley/toolbox/JsonObjectRequest.java b/src/main/java/com/android/volley/toolbox/JsonObjectRequest.java index 2991898..e9dc3d7 100644 --- a/src/main/java/com/android/volley/toolbox/JsonObjectRequest.java +++ b/src/main/java/com/android/volley/toolbox/JsonObjectRequest.java @@ -21,12 +21,10 @@ import com.android.volley.ParseError; import com.android.volley.Response; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; - +import java.io.UnsupportedEncodingException; import org.json.JSONException; import org.json.JSONObject; -import java.io.UnsupportedEncodingException; - /** * A request for retrieving a {@link JSONObject} response body at a given URL, allowing for an * optional {@link JSONObject} to be passed in as part of the request body. @@ -35,38 +33,56 @@ public class JsonObjectRequest extends JsonRequest<JSONObject> { /** * Creates a new request. + * * @param method the HTTP method to use * @param url URL to fetch the JSON from * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and - * indicates no parameters will be posted along with request. + * indicates no parameters will be posted along with request. * @param listener Listener to receive the JSON response * @param errorListener Error listener, or null to ignore errors. */ - public JsonObjectRequest(int method, String url, JSONObject jsonRequest, - Listener<JSONObject> listener, ErrorListener errorListener) { - super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, - errorListener); + public JsonObjectRequest( + int method, + String url, + JSONObject jsonRequest, + Listener<JSONObject> listener, + ErrorListener errorListener) { + super( + method, + url, + (jsonRequest == null) ? null : jsonRequest.toString(), + listener, + errorListener); } /** - * Constructor which defaults to <code>GET</code> if <code>jsonRequest</code> is - * <code>null</code>, <code>POST</code> otherwise. + * Constructor which defaults to <code>GET</code> if <code>jsonRequest</code> is <code>null + * </code> , <code>POST</code> otherwise. * * @see #JsonObjectRequest(int, String, JSONObject, Listener, ErrorListener) */ - public JsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener, + public JsonObjectRequest( + String url, + JSONObject jsonRequest, + Listener<JSONObject> listener, ErrorListener errorListener) { - this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest, - listener, errorListener); + this( + jsonRequest == null ? Method.GET : Method.POST, + url, + jsonRequest, + listener, + errorListener); } @Override protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { try { - String jsonString = new String(response.data, - HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET)); - return Response.success(new JSONObject(jsonString), - HttpHeaderParser.parseCacheHeaders(response)); + String jsonString = + new String( + response.data, + HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET)); + return Response.success( + new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { diff --git a/src/main/java/com/android/volley/toolbox/JsonRequest.java b/src/main/java/com/android/volley/toolbox/JsonRequest.java index f291076..fd395dd 100644 --- a/src/main/java/com/android/volley/toolbox/JsonRequest.java +++ b/src/main/java/com/android/volley/toolbox/JsonRequest.java @@ -16,18 +16,18 @@ package com.android.volley.toolbox; +import android.support.annotation.GuardedBy; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; import com.android.volley.VolleyLog; - import java.io.UnsupportedEncodingException; /** - * A request for retrieving a T type response body at a given URL that also - * optionally sends along a JSON body in the request specified. + * A request for retrieving a T type response body at a given URL that also optionally sends along a + * JSON body in the request specified. * * @param <T> JSON type of response expected */ @@ -37,13 +37,14 @@ public abstract class JsonRequest<T> extends Request<T> { /** Content type for request. */ private static final String PROTOCOL_CONTENT_TYPE = - String.format("application/json; charset=%s", PROTOCOL_CHARSET); + String.format("application/json; charset=%s", PROTOCOL_CHARSET); /** Lock to guard mListener as it is cleared on cancel() and read on delivery. */ private final Object mLock = new Object(); - // @GuardedBy("mLock") + @GuardedBy("mLock") private Listener<T> mListener; + private final String mRequestBody; /** @@ -53,12 +54,16 @@ public abstract class JsonRequest<T> extends Request<T> { * @deprecated Use {@link #JsonRequest(int, String, String, Listener, ErrorListener)}. */ @Deprecated - public JsonRequest(String url, String requestBody, Listener<T> listener, - ErrorListener errorListener) { + public JsonRequest( + String url, String requestBody, Listener<T> listener, ErrorListener errorListener) { this(Method.DEPRECATED_GET_OR_POST, url, requestBody, listener, errorListener); } - public JsonRequest(int method, String url, String requestBody, Listener<T> listener, + public JsonRequest( + int method, + String url, + String requestBody, + Listener<T> listener, ErrorListener errorListener) { super(method, url, errorListener); mListener = listener; @@ -85,20 +90,16 @@ public abstract class JsonRequest<T> extends Request<T> { } @Override - abstract protected Response<T> parseNetworkResponse(NetworkResponse response); + protected abstract Response<T> parseNetworkResponse(NetworkResponse response); - /** - * @deprecated Use {@link #getBodyContentType()}. - */ + /** @deprecated Use {@link #getBodyContentType()}. */ @Deprecated @Override public String getPostBodyContentType() { return getBodyContentType(); } - /** - * @deprecated Use {@link #getBody()}. - */ + /** @deprecated Use {@link #getBody()}. */ @Deprecated @Override public byte[] getPostBody() { @@ -115,7 +116,8 @@ public abstract class JsonRequest<T> extends Request<T> { try { return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET); } catch (UnsupportedEncodingException uee) { - VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", + VolleyLog.wtf( + "Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, PROTOCOL_CHARSET); return null; } diff --git a/src/main/java/com/android/volley/toolbox/NetworkImageView.java b/src/main/java/com/android/volley/toolbox/NetworkImageView.java index 60e4815..a490a79 100644 --- a/src/main/java/com/android/volley/toolbox/NetworkImageView.java +++ b/src/main/java/com/android/volley/toolbox/NetworkImageView.java @@ -1,46 +1,37 @@ /** * Copyright (C) 2013 The Android Open Source Project * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * <p>http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + * <p>Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.android.volley.toolbox; import android.content.Context; +import android.support.annotation.MainThread; import android.text.TextUtils; import android.util.AttributeSet; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; - import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader.ImageContainer; import com.android.volley.toolbox.ImageLoader.ImageListener; -/** - * Handles fetching an image from a URL as well as the life-cycle of the - * associated request. - */ +/** Handles fetching an image from a URL as well as the life-cycle of the associated request. */ public class NetworkImageView extends ImageView { /** The URL of the network image to load */ private String mUrl; - /** - * Resource ID of the image to be used as a placeholder until the network image is loaded. - */ + /** Resource ID of the image to be used as a placeholder until the network image is loaded. */ private int mDefaultImageId; - /** - * Resource ID of the image to be used if the network response fails. - */ + /** Resource ID of the image to be used if the network response fails. */ private int mErrorImageId; /** Local copy of the ImageLoader. */ @@ -66,18 +57,21 @@ public class NetworkImageView extends ImageView { * immediately either set the cached image (if available) or the default image specified by * {@link NetworkImageView#setDefaultImageResId(int)} on the view. * - * NOTE: If applicable, {@link NetworkImageView#setDefaultImageResId(int)} and - * {@link NetworkImageView#setErrorImageResId(int)} should be called prior to calling - * this function. + * <p>NOTE: If applicable, {@link NetworkImageView#setDefaultImageResId(int)} and {@link + * NetworkImageView#setErrorImageResId(int)} should be called prior to calling this function. + * + * <p>Must be called from the main thread. * * @param url The URL that should be loaded into this ImageView. * @param imageLoader ImageLoader that will be used to make the request. */ + @MainThread public void setImageUrl(String url, ImageLoader imageLoader) { + Threads.throwIfNotOnMainThread(); mUrl = url; mImageLoader = imageLoader; // The URL has potentially changed. See if we need to load it. - loadImageIfNecessary(false); + loadImageIfNecessary(/* isInLayoutPass= */ false); } /** @@ -98,6 +92,7 @@ public class NetworkImageView extends ImageView { /** * Loads the image for the view if it isn't already loaded. + * * @param isInLayoutPass True if this was invoked from a layout pass, false otherwise. */ void loadImageIfNecessary(final boolean isInLayoutPass) { @@ -149,45 +144,54 @@ public class NetworkImageView extends ImageView { // from the network. // update the ImageContainer to be the new bitmap container. - mImageContainer = mImageLoader.get(mUrl, - new ImageListener() { - @Override - public void onErrorResponse(VolleyError error) { - if (mErrorImageId != 0) { - setImageResource(mErrorImageId); - } - } - - @Override - public void onResponse(final ImageContainer response, boolean isImmediate) { - // If this was an immediate response that was delivered inside of a layout - // pass do not set the image immediately as it will trigger a requestLayout - // inside of a layout. Instead, defer setting the image by posting back to - // the main thread. - if (isImmediate && isInLayoutPass) { - post(new Runnable() { - @Override - public void run() { - onResponse(response, false); + mImageContainer = + mImageLoader.get( + mUrl, + new ImageListener() { + @Override + public void onErrorResponse(VolleyError error) { + if (mErrorImageId != 0) { + setImageResource(mErrorImageId); + } + } + + @Override + public void onResponse( + final ImageContainer response, boolean isImmediate) { + // If this was an immediate response that was delivered inside of a + // layout + // pass do not set the image immediately as it will trigger a + // requestLayout + // inside of a layout. Instead, defer setting the image by posting + // back to + // the main thread. + if (isImmediate && isInLayoutPass) { + post( + new Runnable() { + @Override + public void run() { + onResponse(response, /* isImmediate= */ false); + } + }); + return; } - }); - return; - } - - if (response.getBitmap() != null) { - setImageBitmap(response.getBitmap()); - } else if (mDefaultImageId != 0) { - setImageResource(mDefaultImageId); - } - } - }, maxWidth, maxHeight, scaleType); + + if (response.getBitmap() != null) { + setImageBitmap(response.getBitmap()); + } else if (mDefaultImageId != 0) { + setImageResource(mDefaultImageId); + } + } + }, + maxWidth, + maxHeight, + scaleType); } private void setDefaultImageOrNull() { - if(mDefaultImageId != 0) { + if (mDefaultImageId != 0) { setImageResource(mDefaultImageId); - } - else { + } else { setImageBitmap(null); } } @@ -195,7 +199,7 @@ public class NetworkImageView extends ImageView { @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); - loadImageIfNecessary(true); + loadImageIfNecessary(/* isInLayoutPass= */ true); } @Override diff --git a/src/main/java/com/android/volley/toolbox/NoCache.java b/src/main/java/com/android/volley/toolbox/NoCache.java index ab66254..51f9945 100644 --- a/src/main/java/com/android/volley/toolbox/NoCache.java +++ b/src/main/java/com/android/volley/toolbox/NoCache.java @@ -18,13 +18,10 @@ package com.android.volley.toolbox; import com.android.volley.Cache; -/** - * A cache that doesn't. - */ +/** A cache that doesn't. */ public class NoCache implements Cache { @Override - public void clear() { - } + public void clear() {} @Override public Entry get(String key) { @@ -32,18 +29,14 @@ public class NoCache implements Cache { } @Override - public void put(String key, Entry entry) { - } + public void put(String key, Entry entry) {} @Override - public void invalidate(String key, boolean fullExpire) { - } + public void invalidate(String key, boolean fullExpire) {} @Override - public void remove(String key) { - } + public void remove(String key) {} @Override - public void initialize() { - } + public void initialize() {} } diff --git a/src/main/java/com/android/volley/toolbox/PoolingByteArrayOutputStream.java b/src/main/java/com/android/volley/toolbox/PoolingByteArrayOutputStream.java index 9971566..bdcc45e 100644 --- a/src/main/java/com/android/volley/toolbox/PoolingByteArrayOutputStream.java +++ b/src/main/java/com/android/volley/toolbox/PoolingByteArrayOutputStream.java @@ -46,7 +46,7 @@ public class PoolingByteArrayOutputStream extends ByteArrayOutputStream { * expand. * * @param size initial size for the underlying byte array. The value will be pinned to a default - * minimum size. + * minimum size. */ public PoolingByteArrayOutputStream(ByteArrayPool pool, int size) { mPool = pool; @@ -65,9 +65,8 @@ public class PoolingByteArrayOutputStream extends ByteArrayOutputStream { mPool.returnBuf(buf); } - /** - * Ensures there is enough space in the buffer for the given number of additional bytes. - */ + /** Ensures there is enough space in the buffer for the given number of additional bytes. */ + @SuppressWarnings("UnsafeFinalization") private void expand(int i) { /* Can the buffer handle @i more bytes, if not expand it */ if (count + i <= buf.length) { diff --git a/src/main/java/com/android/volley/toolbox/RequestFuture.java b/src/main/java/com/android/volley/toolbox/RequestFuture.java index 173c44c..f9cbce2 100644 --- a/src/main/java/com/android/volley/toolbox/RequestFuture.java +++ b/src/main/java/com/android/volley/toolbox/RequestFuture.java @@ -16,10 +16,10 @@ package com.android.volley.toolbox; +import android.os.SystemClock; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; - import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; @@ -28,7 +28,8 @@ import java.util.concurrent.TimeoutException; /** * A Future that represents a Volley request. * - * Used by providing as your response and error listeners. For example: + * <p>Used by providing as your response and error listeners. For example: + * * <pre> * RequestFuture<JSONObject> future = RequestFuture.newFuture(); * MyRequest request = new MyRequest(URL, future, future); @@ -51,15 +52,14 @@ import java.util.concurrent.TimeoutException; * * @param <T> The type of parsed response this future expects. */ -public class RequestFuture<T> implements Future<T>, Response.Listener<T>, - Response.ErrorListener { +public class RequestFuture<T> implements Future<T>, Response.Listener<T>, Response.ErrorListener { private Request<?> mRequest; private boolean mResultReceived = false; private T mResult; private VolleyError mException; public static <E> RequestFuture<E> newFuture() { - return new RequestFuture<E>(); + return new RequestFuture<>(); } private RequestFuture() {} @@ -85,7 +85,7 @@ public class RequestFuture<T> implements Future<T>, Response.Listener<T>, @Override public T get() throws InterruptedException, ExecutionException { try { - return doGet(null); + return doGet(/* timeoutMs= */ null); } catch (TimeoutException e) { throw new AssertionError(e); } @@ -108,9 +108,16 @@ public class RequestFuture<T> implements Future<T>, Response.Listener<T>, } if (timeoutMs == null) { - wait(0); + while (!isDone()) { + wait(0); + } } else if (timeoutMs > 0) { - wait(timeoutMs); + long nowMs = SystemClock.uptimeMillis(); + long deadlineMs = nowMs + timeoutMs; + while (!isDone() && nowMs < deadlineMs) { + wait(deadlineMs - nowMs); + nowMs = SystemClock.uptimeMillis(); + } } if (mException != null) { @@ -150,4 +157,3 @@ public class RequestFuture<T> implements Future<T>, Response.Listener<T>, notifyAll(); } } - diff --git a/src/main/java/com/android/volley/toolbox/StringRequest.java b/src/main/java/com/android/volley/toolbox/StringRequest.java index 9deba1d..0fbab14 100644 --- a/src/main/java/com/android/volley/toolbox/StringRequest.java +++ b/src/main/java/com/android/volley/toolbox/StringRequest.java @@ -16,23 +16,21 @@ package com.android.volley.toolbox; +import android.support.annotation.GuardedBy; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; - import java.io.UnsupportedEncodingException; -/** - * A canned request for retrieving the response body at a given URL as a String. - */ +/** A canned request for retrieving the response body at a given URL as a String. */ public class StringRequest extends Request<String> { /** Lock to guard mListener as it is cleared on cancel() and read on delivery. */ private final Object mLock = new Object(); - // @GuardedBy("mLock") + @GuardedBy("mLock") private Listener<String> mListener; /** @@ -43,8 +41,8 @@ public class StringRequest extends Request<String> { * @param listener Listener to receive the String response * @param errorListener Error listener, or null to ignore errors */ - public StringRequest(int method, String url, Listener<String> listener, - ErrorListener errorListener) { + public StringRequest( + int method, String url, Listener<String> listener, ErrorListener errorListener) { super(method, url, errorListener); mListener = listener; } @@ -80,11 +78,15 @@ public class StringRequest extends Request<String> { } @Override + @SuppressWarnings("DefaultCharset") protected Response<String> parseNetworkResponse(NetworkResponse response) { String parsed; try { parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); } catch (UnsupportedEncodingException e) { + // Since minSdkVersion = 8, we can't call + // new String(response.data, Charset.defaultCharset()) + // So suppress the warning instead. parsed = new String(response.data); } return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); diff --git a/src/main/java/com/android/volley/toolbox/Threads.java b/src/main/java/com/android/volley/toolbox/Threads.java new file mode 100644 index 0000000..66c3e41 --- /dev/null +++ b/src/main/java/com/android/volley/toolbox/Threads.java @@ -0,0 +1,13 @@ +package com.android.volley.toolbox; + +import android.os.Looper; + +final class Threads { + private Threads() {} + + static void throwIfNotOnMainThread() { + if (Looper.myLooper() != Looper.getMainLooper()) { + throw new IllegalStateException("Must be invoked from the main thread."); + } + } +} diff --git a/src/main/java/com/android/volley/toolbox/Volley.java b/src/main/java/com/android/volley/toolbox/Volley.java index 6ec08b1..1982802 100644 --- a/src/main/java/com/android/volley/toolbox/Volley.java +++ b/src/main/java/com/android/volley/toolbox/Volley.java @@ -21,10 +21,8 @@ import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.http.AndroidHttpClient; import android.os.Build; - import com.android.volley.Network; import com.android.volley.RequestQueue; - import java.io.File; public class Volley { @@ -52,13 +50,15 @@ public class Volley { String userAgent = "volley/0"; try { String packageName = context.getPackageName(); - PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); + PackageInfo info = + context.getPackageManager().getPackageInfo(packageName, /* flags= */ 0); userAgent = packageName + "/" + info.versionCode; } catch (NameNotFoundException e) { } - network = new BasicNetwork( - new HttpClientStack(AndroidHttpClient.newInstance(userAgent))); + network = + new BasicNetwork( + new HttpClientStack(AndroidHttpClient.newInstance(userAgent))); } } else { network = new BasicNetwork(stack); @@ -74,7 +74,7 @@ public class Volley { * @param stack An {@link HttpStack} to use for the network, or null for default. * @return A started {@link RequestQueue} instance. * @deprecated Use {@link #newRequestQueue(Context, BaseHttpStack)} instead to avoid depending - * on Apache HTTP. This method may be removed in a future release of Volley. + * on Apache HTTP. This method may be removed in a future release of Volley. */ @Deprecated @SuppressWarnings("deprecation") |