1 package org.robolectric.shadows; 2 3 import static org.robolectric.shadow.api.Shadow.newInstanceOf; 4 5 import android.net.http.HttpResponseCache; 6 import java.io.File; 7 import java.net.CacheResponse; 8 import java.net.URI; 9 import java.net.URLConnection; 10 import java.util.List; 11 import java.util.Map; 12 import org.robolectric.Shadows; 13 import org.robolectric.annotation.Implementation; 14 import org.robolectric.annotation.Implements; 15 16 @SuppressWarnings({"UnusedDeclaration"}) 17 @Implements(value = HttpResponseCache.class, callThroughByDefault = false) 18 public class ShadowHttpResponseCache { 19 private static final Object LOCK = new Object(); 20 21 static ShadowHttpResponseCache installed = null; 22 23 private HttpResponseCache originalObject; 24 private File directory; 25 private long maxSize; 26 private int requestCount = 0; 27 private int hitCount = 0; 28 private int networkCount = 0; 29 30 @Implementation 31 public static HttpResponseCache install(File directory, long maxSize) { 32 HttpResponseCache cache = newInstanceOf(HttpResponseCache.class); 33 ShadowHttpResponseCache shadowCache = Shadows.shadowOf(cache); 34 shadowCache.originalObject = cache; 35 shadowCache.directory = directory; 36 shadowCache.maxSize = maxSize; 37 synchronized (LOCK) { 38 installed = shadowCache; 39 return cache; 40 } 41 } 42 43 @Implementation 44 public static HttpResponseCache getInstalled() { 45 synchronized (LOCK) { 46 return (installed != null) ? installed.originalObject : null; 47 } 48 } 49 50 @Implementation 51 public long maxSize() { 52 return maxSize; 53 } 54 55 @Implementation 56 public long size() { 57 return 0; 58 } 59 60 @Implementation 61 public void close() { 62 synchronized (LOCK) { 63 installed = null; 64 } 65 } 66 67 @Implementation 68 public void delete() { 69 close(); 70 } 71 72 @Implementation 73 public int getHitCount() { 74 return hitCount; 75 } 76 77 @Implementation 78 public int getNetworkCount() { 79 return networkCount; 80 } 81 82 @Implementation 83 public int getRequestCount() { 84 return requestCount; 85 } 86 87 @Implementation 88 public CacheResponse get(URI uri, String requestMethod, Map<String, List<String>> requestHeaders) { 89 requestCount += 1; 90 networkCount += 1; // Always pretend we had a cache miss and had to fall back to the network. 91 return null; 92 } 93 94 @Implementation 95 public CacheResponse put(URI uri, URLConnection urlConnection) { 96 // Do not cache any data. All requests will be a miss. 97 return null; 98 } 99 } 100