parseNetworkResponse(NetworkResponse response);
70 |
71 | /**
72 | * @deprecated Use {@link #getBodyContentType()}.
73 | */
74 | @Override
75 | public String getPostBodyContentType() {
76 | return getBodyContentType();
77 | }
78 |
79 | /**
80 | * @deprecated Use {@link #getBody()}.
81 | */
82 | @Override
83 | public byte[] getPostBody() {
84 | return getBody();
85 | }
86 |
87 | @Override
88 | public String getBodyContentType() {
89 | return PROTOCOL_CONTENT_TYPE;
90 | }
91 |
92 | @Override
93 | public byte[] getBody() {
94 | try {
95 | return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
96 | } catch (UnsupportedEncodingException uee) {
97 | VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
98 | mRequestBody, PROTOCOL_CHARSET);
99 | return null;
100 | }
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/volley/src/main/java/com/android/volley/toolbox/NoCache.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2011 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.volley.toolbox;
18 |
19 | import com.android.volley.Cache;
20 |
21 | /**
22 | * A cache that doesn't.
23 | */
24 | public class NoCache implements Cache {
25 | @Override
26 | public void clear() {
27 | }
28 |
29 | @Override
30 | public Entry get(String key) {
31 | return null;
32 | }
33 |
34 | @Override
35 | public void put(String key, Entry entry) {
36 | }
37 |
38 | @Override
39 | public void invalidate(String key, boolean fullExpire) {
40 | }
41 |
42 | @Override
43 | public void remove(String key) {
44 | }
45 |
46 | @Override
47 | public void initialize() {
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/volley/src/main/java/com/android/volley/toolbox/PoolingByteArrayOutputStream.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2012 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.volley.toolbox;
18 |
19 | import java.io.ByteArrayOutputStream;
20 | import java.io.IOException;
21 |
22 | /**
23 | * A variation of {@link java.io.ByteArrayOutputStream} that uses a pool of byte[] buffers instead
24 | * of always allocating them fresh, saving on heap churn.
25 | */
26 | public class PoolingByteArrayOutputStream extends ByteArrayOutputStream {
27 | /**
28 | * If the {@link #PoolingByteArrayOutputStream(ByteArrayPool)} constructor is called, this is
29 | * the default size to which the underlying byte array is initialized.
30 | */
31 | private static final int DEFAULT_SIZE = 256;
32 |
33 | private final ByteArrayPool mPool;
34 |
35 | /**
36 | * Constructs a new PoolingByteArrayOutputStream with a default size. If more bytes are written
37 | * to this instance, the underlying byte array will expand.
38 | */
39 | public PoolingByteArrayOutputStream(ByteArrayPool pool) {
40 | this(pool, DEFAULT_SIZE);
41 | }
42 |
43 | /**
44 | * Constructs a new {@code ByteArrayOutputStream} with a default size of {@code size} bytes. If
45 | * more than {@code size} bytes are written to this instance, the underlying byte array will
46 | * expand.
47 | *
48 | * @param size initial size for the underlying byte array. The value will be pinned to a default
49 | * minimum size.
50 | */
51 | public PoolingByteArrayOutputStream(ByteArrayPool pool, int size) {
52 | mPool = pool;
53 | buf = mPool.getBuf(Math.max(size, DEFAULT_SIZE));
54 | }
55 |
56 | @Override
57 | public void close() throws IOException {
58 | mPool.returnBuf(buf);
59 | buf = null;
60 | super.close();
61 | }
62 |
63 | @Override
64 | public void finalize() {
65 | mPool.returnBuf(buf);
66 | }
67 |
68 | /**
69 | * Ensures there is enough space in the buffer for the given number of additional bytes.
70 | */
71 | private void expand(int i) {
72 | /* Can the buffer handle @i more bytes, if not expand it */
73 | if (count + i <= buf.length) {
74 | return;
75 | }
76 | byte[] newbuf = mPool.getBuf((count + i) * 2);
77 | System.arraycopy(buf, 0, newbuf, 0, count);
78 | mPool.returnBuf(buf);
79 | buf = newbuf;
80 | }
81 |
82 | @Override
83 | public synchronized void write(byte[] buffer, int offset, int len) {
84 | expand(len);
85 | super.write(buffer, offset, len);
86 | }
87 |
88 | @Override
89 | public synchronized void write(int oneByte) {
90 | expand(1);
91 | super.write(oneByte);
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/volley/src/main/java/com/android/volley/toolbox/RequestFuture.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2011 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.volley.toolbox;
18 |
19 | import com.android.volley.Request;
20 | import com.android.volley.Response;
21 | import com.android.volley.VolleyError;
22 |
23 | import java.util.concurrent.ExecutionException;
24 | import java.util.concurrent.Future;
25 | import java.util.concurrent.TimeUnit;
26 | import java.util.concurrent.TimeoutException;
27 |
28 | /**
29 | * A Future that represents a Volley request.
30 | *
31 | * Used by providing as your response and error listeners. For example:
32 | *
33 | * RequestFuture<JSONObject> future = RequestFuture.newFuture();
34 | * MyRequest request = new MyRequest(URL, future, future);
35 | *
36 | * // If you want to be able to cancel the request:
37 | * future.setRequest(requestQueue.add(request));
38 | *
39 | * // Otherwise:
40 | * requestQueue.add(request);
41 | *
42 | * try {
43 | * JSONObject response = future.get();
44 | * // do something with response
45 | * } catch (InterruptedException e) {
46 | * // handle the error
47 | * } catch (ExecutionException e) {
48 | * // handle the error
49 | * }
50 | *
51 | *
52 | * @param The type of parsed response this future expects.
53 | */
54 | public class RequestFuture implements Future, Response.Listener,
55 | Response.ErrorListener {
56 | private Request> mRequest;
57 | private boolean mResultReceived = false;
58 | private T mResult;
59 | private VolleyError mException;
60 |
61 | public static RequestFuture newFuture() {
62 | return new RequestFuture();
63 | }
64 |
65 | private RequestFuture() {}
66 |
67 | public void setRequest(Request> request) {
68 | mRequest = request;
69 | }
70 |
71 | @Override
72 | public synchronized boolean cancel(boolean mayInterruptIfRunning) {
73 | if (mRequest == null) {
74 | return false;
75 | }
76 |
77 | if (!isDone()) {
78 | mRequest.cancel();
79 | return true;
80 | } else {
81 | return false;
82 | }
83 | }
84 |
85 | @Override
86 | public T get() throws InterruptedException, ExecutionException {
87 | try {
88 | return doGet(null);
89 | } catch (TimeoutException e) {
90 | throw new AssertionError(e);
91 | }
92 | }
93 |
94 | @Override
95 | public T get(long timeout, TimeUnit unit)
96 | throws InterruptedException, ExecutionException, TimeoutException {
97 | return doGet(TimeUnit.MILLISECONDS.convert(timeout, unit));
98 | }
99 |
100 | private synchronized T doGet(Long timeoutMs)
101 | throws InterruptedException, ExecutionException, TimeoutException {
102 | if (mException != null) {
103 | throw new ExecutionException(mException);
104 | }
105 |
106 | if (mResultReceived) {
107 | return mResult;
108 | }
109 |
110 | if (timeoutMs == null) {
111 | wait(0);
112 | } else if (timeoutMs > 0) {
113 | wait(timeoutMs);
114 | }
115 |
116 | if (mException != null) {
117 | throw new ExecutionException(mException);
118 | }
119 |
120 | if (!mResultReceived) {
121 | throw new TimeoutException();
122 | }
123 |
124 | return mResult;
125 | }
126 |
127 | @Override
128 | public boolean isCancelled() {
129 | if (mRequest == null) {
130 | return false;
131 | }
132 | return mRequest.isCanceled();
133 | }
134 |
135 | @Override
136 | public synchronized boolean isDone() {
137 | return mResultReceived || mException != null || isCancelled();
138 | }
139 |
140 | @Override
141 | public synchronized void onResponse(T response) {
142 | mResultReceived = true;
143 | mResult = response;
144 | notifyAll();
145 | }
146 |
147 | @Override
148 | public synchronized void onErrorResponse(VolleyError error) {
149 | mException = error;
150 | notifyAll();
151 | }
152 | }
153 |
154 |
--------------------------------------------------------------------------------
/volley/src/main/java/com/android/volley/toolbox/StringRequest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2011 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.volley.toolbox;
18 |
19 | import com.android.volley.NetworkResponse;
20 | import com.android.volley.Request;
21 | import com.android.volley.Response;
22 | import com.android.volley.Response.ErrorListener;
23 | import com.android.volley.Response.Listener;
24 |
25 | import java.io.UnsupportedEncodingException;
26 |
27 | /**
28 | * A canned request for retrieving the response body at a given URL as a String.
29 | */
30 | public class StringRequest extends Request {
31 | private final Listener mListener;
32 |
33 | /**
34 | * Creates a new request with the given method.
35 | *
36 | * @param method the request {@link Method} to use
37 | * @param url URL to fetch the string at
38 | * @param listener Listener to receive the String response
39 | * @param errorListener Error listener, or null to ignore errors
40 | */
41 | public StringRequest(int method, String url, Listener listener,
42 | ErrorListener errorListener) {
43 | super(method, url, errorListener);
44 | mListener = listener;
45 | }
46 |
47 | /**
48 | * Creates a new GET request.
49 | *
50 | * @param url URL to fetch the string at
51 | * @param listener Listener to receive the String response
52 | * @param errorListener Error listener, or null to ignore errors
53 | */
54 | public StringRequest(String url, Listener listener, ErrorListener errorListener) {
55 | this(Method.GET, url, listener, errorListener);
56 | }
57 |
58 | @Override
59 | protected void deliverResponse(String response) {
60 | mListener.onResponse(response);
61 | }
62 |
63 | @Override
64 | protected Response parseNetworkResponse(NetworkResponse response) {
65 | String parsed;
66 | try {
67 | parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
68 | } catch (UnsupportedEncodingException e) {
69 | parsed = new String(response.data);
70 | }
71 | return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/volley/src/main/java/com/android/volley/toolbox/Volley.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2012 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.volley.toolbox;
18 |
19 | import android.content.Context;
20 | import android.content.pm.PackageInfo;
21 | import android.content.pm.PackageManager.NameNotFoundException;
22 | import android.net.http.AndroidHttpClient;
23 | import android.os.Build;
24 |
25 | import com.android.volley.Network;
26 | import com.android.volley.RequestQueue;
27 |
28 | import java.io.File;
29 |
30 | public class Volley {
31 |
32 | /** Default on-disk cache directory. */
33 | private static final String DEFAULT_CACHE_DIR = "volley";
34 |
35 | /**
36 | * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
37 | *
38 | * @param context A {@link Context} to use for creating the cache dir.
39 | * @param stack An {@link HttpStack} to use for the network, or null for default.
40 | * @return A started {@link RequestQueue} instance.
41 | */
42 | public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
43 | File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
44 |
45 | String userAgent = "volley/0";
46 | try {
47 | String packageName = context.getPackageName();
48 | PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
49 | userAgent = packageName + "/" + info.versionCode;
50 | } catch (NameNotFoundException e) {
51 | }
52 |
53 | if (stack == null) {
54 | if (Build.VERSION.SDK_INT >= 9) {
55 | stack = new HurlStack();
56 | } else {
57 | // Prior to Gingerbread, HttpUrlConnection was unreliable.
58 | // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
59 | stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
60 | }
61 | }
62 |
63 | Network network = new BasicNetwork(stack);
64 |
65 | RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
66 | queue.start();
67 |
68 | return queue;
69 | }
70 |
71 | /**
72 | * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
73 | *
74 | * @param context A {@link Context} to use for creating the cache dir.
75 | * @return A started {@link RequestQueue} instance.
76 | */
77 | public static RequestQueue newRequestQueue(Context context) {
78 | return newRequestQueue(context, null);
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/volley/src/test/java/com/android/volley/CacheDispatcherTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2011 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.volley;
18 |
19 | import com.android.volley.mock.MockCache;
20 | import com.android.volley.mock.MockRequest;
21 | import com.android.volley.mock.MockResponseDelivery;
22 | import com.android.volley.mock.WaitableQueue;
23 | import com.android.volley.utils.CacheTestUtils;
24 |
25 | import org.junit.After;
26 | import org.junit.Before;
27 | import org.junit.Test;
28 | import org.junit.runner.RunWith;
29 | import org.robolectric.RobolectricTestRunner;
30 |
31 | import static org.junit.Assert.*;
32 |
33 | @RunWith(RobolectricTestRunner.class)
34 | @SuppressWarnings("rawtypes")
35 | public class CacheDispatcherTest {
36 | private CacheDispatcher mDispatcher;
37 | private WaitableQueue mCacheQueue;
38 | private WaitableQueue mNetworkQueue;
39 | private MockCache mCache;
40 | private MockResponseDelivery mDelivery;
41 | private MockRequest mRequest;
42 |
43 | private static final long TIMEOUT_MILLIS = 5000;
44 |
45 | @Before public void setUp() throws Exception {
46 | mCacheQueue = new WaitableQueue();
47 | mNetworkQueue = new WaitableQueue();
48 | mCache = new MockCache();
49 | mDelivery = new MockResponseDelivery();
50 |
51 | mRequest = new MockRequest();
52 |
53 | mDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
54 | mDispatcher.start();
55 | }
56 |
57 | @After public void tearDown() throws Exception {
58 | mDispatcher.quit();
59 | mDispatcher.join();
60 | }
61 |
62 | // A cancelled request should not be processed at all.
63 | @Test public void cancelledRequest() throws Exception {
64 | mRequest.cancel();
65 | mCacheQueue.add(mRequest);
66 | mCacheQueue.waitUntilEmpty(TIMEOUT_MILLIS);
67 | assertFalse(mCache.getCalled);
68 | assertFalse(mDelivery.wasEitherResponseCalled());
69 | }
70 |
71 | // A cache miss does not post a response and puts the request on the network queue.
72 | @Test public void cacheMiss() throws Exception {
73 | mCacheQueue.add(mRequest);
74 | mCacheQueue.waitUntilEmpty(TIMEOUT_MILLIS);
75 | assertFalse(mDelivery.wasEitherResponseCalled());
76 | assertTrue(mNetworkQueue.size() > 0);
77 | Request request = mNetworkQueue.take();
78 | assertNull(request.getCacheEntry());
79 | }
80 |
81 | // A non-expired cache hit posts a response and does not queue to the network.
82 | @Test public void nonExpiredCacheHit() throws Exception {
83 | Cache.Entry entry = CacheTestUtils.makeRandomCacheEntry(null, false, false);
84 | mCache.setEntryToReturn(entry);
85 | mCacheQueue.add(mRequest);
86 | mCacheQueue.waitUntilEmpty(TIMEOUT_MILLIS);
87 | assertTrue(mDelivery.postResponse_called);
88 | assertFalse(mDelivery.postError_called);
89 | }
90 |
91 | // A soft-expired cache hit posts a response and queues to the network.
92 | @Test public void softExpiredCacheHit() throws Exception {
93 | Cache.Entry entry = CacheTestUtils.makeRandomCacheEntry(null, false, true);
94 | mCache.setEntryToReturn(entry);
95 | mCacheQueue.add(mRequest);
96 | mCacheQueue.waitUntilEmpty(TIMEOUT_MILLIS);
97 | assertTrue(mDelivery.postResponse_called);
98 | assertFalse(mDelivery.postError_called);
99 | assertTrue(mNetworkQueue.size() > 0);
100 | Request request = mNetworkQueue.take();
101 | assertSame(entry, request.getCacheEntry());
102 | }
103 |
104 | // An expired cache hit does not post a response and queues to the network.
105 | @Test public void expiredCacheHit() throws Exception {
106 | Cache.Entry entry = CacheTestUtils.makeRandomCacheEntry(null, true, true);
107 | mCache.setEntryToReturn(entry);
108 | mCacheQueue.add(mRequest);
109 | mCacheQueue.waitUntilEmpty(TIMEOUT_MILLIS);
110 | assertFalse(mDelivery.wasEitherResponseCalled());
111 | assertTrue(mNetworkQueue.size() > 0);
112 | Request request = mNetworkQueue.take();
113 | assertSame(entry, request.getCacheEntry());
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/volley/src/test/java/com/android/volley/NetworkDispatcherTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2011 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.volley;
18 |
19 | import com.android.volley.mock.MockCache;
20 | import com.android.volley.mock.MockNetwork;
21 | import com.android.volley.mock.MockRequest;
22 | import com.android.volley.mock.MockResponseDelivery;
23 | import com.android.volley.mock.WaitableQueue;
24 | import org.junit.After;
25 | import org.junit.Before;
26 | import org.junit.Test;
27 | import org.junit.runner.RunWith;
28 | import org.robolectric.RobolectricTestRunner;
29 |
30 | import java.util.Arrays;
31 |
32 | import static org.junit.Assert.*;
33 |
34 | @RunWith(RobolectricTestRunner.class)
35 | public class NetworkDispatcherTest {
36 | private NetworkDispatcher mDispatcher;
37 | private MockResponseDelivery mDelivery;
38 | private WaitableQueue mNetworkQueue;
39 | private MockNetwork mNetwork;
40 | private MockCache mCache;
41 | private MockRequest mRequest;
42 |
43 | private static final byte[] CANNED_DATA = "Ceci n'est pas une vraie reponse".getBytes();
44 | private static final long TIMEOUT_MILLIS = 5000;
45 |
46 | @Before public void setUp() throws Exception {
47 | mDelivery = new MockResponseDelivery();
48 | mNetworkQueue = new WaitableQueue();
49 | mNetwork = new MockNetwork();
50 | mCache = new MockCache();
51 | mRequest = new MockRequest();
52 | mDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork, mCache, mDelivery);
53 | mDispatcher.start();
54 | }
55 |
56 | @After public void tearDown() throws Exception {
57 | mDispatcher.quit();
58 | mDispatcher.join();
59 | }
60 |
61 | @Test public void successPostsResponse() throws Exception {
62 | mNetwork.setDataToReturn(CANNED_DATA);
63 | mNetwork.setNumExceptionsToThrow(0);
64 | mNetworkQueue.add(mRequest);
65 | mNetworkQueue.waitUntilEmpty(TIMEOUT_MILLIS);
66 | assertFalse(mDelivery.postError_called);
67 | assertTrue(mDelivery.postResponse_called);
68 | Response> response = mDelivery.responsePosted;
69 | assertNotNull(response);
70 | assertTrue(response.isSuccess());
71 | assertTrue(Arrays.equals((byte[])response.result, CANNED_DATA));
72 | }
73 |
74 | @Test public void exceptionPostsError() throws Exception {
75 | mNetwork.setNumExceptionsToThrow(MockNetwork.ALWAYS_THROW_EXCEPTIONS);
76 | mNetworkQueue.add(mRequest);
77 | mNetworkQueue.waitUntilEmpty(TIMEOUT_MILLIS);
78 | assertFalse(mDelivery.postResponse_called);
79 | assertTrue(mDelivery.postError_called);
80 | }
81 |
82 | @Test public void shouldCacheFalse() throws Exception {
83 | mRequest.setShouldCache(false);
84 | mNetworkQueue.add(mRequest);
85 | mNetworkQueue.waitUntilEmpty(TIMEOUT_MILLIS);
86 | assertFalse(mCache.putCalled);
87 | }
88 |
89 | @Test public void shouldCacheTrue() throws Exception {
90 | mNetwork.setDataToReturn(CANNED_DATA);
91 | mRequest.setShouldCache(true);
92 | mRequest.setCacheKey("bananaphone");
93 | mNetworkQueue.add(mRequest);
94 | mNetworkQueue.waitUntilEmpty(TIMEOUT_MILLIS);
95 | assertTrue(mCache.putCalled);
96 | assertNotNull(mCache.entryPut);
97 | assertTrue(Arrays.equals(mCache.entryPut.data, CANNED_DATA));
98 | assertEquals("bananaphone", mCache.keyPut);
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/volley/src/test/java/com/android/volley/RequestQueueTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2011 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.volley;
18 |
19 | import com.android.volley.mock.ShadowSystemClock;
20 | import com.android.volley.toolbox.NoCache;
21 | import com.android.volley.utils.ImmediateResponseDelivery;
22 | import org.junit.Before;
23 | import org.junit.Test;
24 | import org.junit.runner.RunWith;
25 | import org.mockito.Mock;
26 | import org.robolectric.RobolectricTestRunner;
27 | import org.robolectric.annotation.Config;
28 |
29 | import static org.junit.Assert.*;
30 | import static org.mockito.Mockito.*;
31 | import static org.mockito.MockitoAnnotations.initMocks;
32 |
33 | /**
34 | * Unit tests for RequestQueue, with all dependencies mocked out
35 | */
36 | @RunWith(RobolectricTestRunner.class)
37 | @Config(shadows = {ShadowSystemClock.class})
38 | public class RequestQueueTest {
39 |
40 | private ResponseDelivery mDelivery;
41 | @Mock private Network mMockNetwork;
42 |
43 | @Before public void setUp() throws Exception {
44 | mDelivery = new ImmediateResponseDelivery();
45 | initMocks(this);
46 | }
47 |
48 | @Test public void cancelAll_onlyCorrectTag() throws Exception {
49 | RequestQueue queue = new RequestQueue(new NoCache(), mMockNetwork, 0, mDelivery);
50 | Object tagA = new Object();
51 | Object tagB = new Object();
52 | Request req1 = mock(Request.class);
53 | when(req1.getTag()).thenReturn(tagA);
54 | Request req2 = mock(Request.class);
55 | when(req2.getTag()).thenReturn(tagB);
56 | Request req3 = mock(Request.class);
57 | when(req3.getTag()).thenReturn(tagA);
58 | Request req4 = mock(Request.class);
59 | when(req4.getTag()).thenReturn(tagA);
60 |
61 | queue.add(req1); // A
62 | queue.add(req2); // B
63 | queue.add(req3); // A
64 | queue.cancelAll(tagA);
65 | queue.add(req4); // A
66 |
67 | verify(req1).cancel(); // A cancelled
68 | verify(req3).cancel(); // A cancelled
69 | verify(req2, never()).cancel(); // B not cancelled
70 | verify(req4, never()).cancel(); // A added after cancel not cancelled
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/volley/src/test/java/com/android/volley/RequestTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2011 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.volley;
18 |
19 | import com.android.volley.Request.Priority;
20 | import org.junit.Test;
21 | import org.junit.runner.RunWith;
22 | import org.robolectric.RobolectricTestRunner;
23 |
24 | import static org.junit.Assert.*;
25 |
26 | @RunWith(RobolectricTestRunner.class)
27 | public class RequestTest {
28 |
29 | @Test public void compareTo() {
30 | int sequence = 0;
31 | TestRequest low = new TestRequest(Priority.LOW);
32 | low.setSequence(sequence++);
33 | TestRequest low2 = new TestRequest(Priority.LOW);
34 | low2.setSequence(sequence++);
35 | TestRequest high = new TestRequest(Priority.HIGH);
36 | high.setSequence(sequence++);
37 | TestRequest immediate = new TestRequest(Priority.IMMEDIATE);
38 | immediate.setSequence(sequence++);
39 |
40 | // "Low" should sort higher because it's really processing order.
41 | assertTrue(low.compareTo(high) > 0);
42 | assertTrue(high.compareTo(low) < 0);
43 | assertTrue(low.compareTo(low2) < 0);
44 | assertTrue(low.compareTo(immediate) > 0);
45 | assertTrue(immediate.compareTo(high) < 0);
46 | }
47 |
48 | private class TestRequest extends Request