Java Code Examples for com.android.volley.Cache#Entry

The following examples show how to use com.android.volley.Cache#Entry . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpHeaderParserTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void parseCaseInsensitive() {

        long now = System.currentTimeMillis();

        Header[] headersArray = new Header[5];
        headersArray[0] = new BasicHeader("eTAG", "Yow!");
        headersArray[1] = new BasicHeader("DATE", rfc1123Date(now));
        headersArray[2] = new BasicHeader("expires", rfc1123Date(now + ONE_HOUR_MILLIS));
        headersArray[3] = new BasicHeader("cache-control", "public, max-age=86400");
        headersArray[4] = new BasicHeader("content-type", "text/plain");

        Map<String, String> headers = BasicNetwork.convertHeaders(headersArray);
        NetworkResponse response = new NetworkResponse(0, null, headers, false);
        Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);

        assertNotNull(entry);
        assertEquals("Yow!", entry.etag);
        assertEqualsWithin(now + ONE_DAY_MILLIS, entry.ttl, ONE_MINUTE_MILLIS);
        assertEquals(entry.softTtl, entry.ttl);
        assertEquals("ISO-8859-1", HttpHeaderParser.parseCharset(headers));
    }
 
Example 2
Source File: OkNetwork.java    From OkVolley with Apache License 2.0 6 votes vote down vote up
private void addCacheHeaders(Map<String, String> headers, Cache.Entry entry) {
    // If there's no cache entry, we're done.
    if (entry == null) {
        return;
    }

    if (entry.etag != null) {
        headers.put("If-None-Match", entry.etag);
    }

    if (entry.serverDate > 0) {
        Date refTime = new Date(entry.serverDate);
        final SimpleDateFormat formatter = DateFormatHolder.formatFor(PATTERN_RFC1036);
        headers.put("If-Modified-Since", formatter.format(refTime));
    }
}
 
Example 3
Source File: DiskBasedCacheTest.java    From android-discourse with Apache License 2.0 6 votes vote down vote up
public void testCacheHeaderSerialization() throws Exception {
    Cache.Entry e = new Cache.Entry();
    e.data = new byte[8];
    e.serverDate = 1234567L;
    e.ttl = 9876543L;
    e.softTtl = 8765432L;
    e.etag = "etag";
    e.responseHeaders = new HashMap<String, String>();
    e.responseHeaders.put("fruit", "banana");

    CacheHeader first = new CacheHeader("my-magical-key", e);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    first.writeHeader(baos);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    CacheHeader second = CacheHeader.readHeader(bais);

    assertEquals(first.key, second.key);
    assertEquals(first.serverDate, second.serverDate);
    assertEquals(first.ttl, second.ttl);
    assertEquals(first.softTtl, second.softTtl);
    assertEquals(first.etag, second.etag);
    assertEquals(first.responseHeaders, second.responseHeaders);
}
 
Example 4
Source File: DiskBasedCacheTest.java    From volley with Apache License 2.0 6 votes vote down vote up
@Test
public void testLargeEntryDoesntClearCache() {
    // Writing a large entry to an empty cache should succeed
    Cache.Entry largeEntry = randomData(MAX_SIZE - getEntrySizeOnDisk("largeEntry") - 1);
    cache.put("largeEntry", largeEntry);

    assertThatEntriesAreEqual(cache.get("largeEntry"), largeEntry);

    // Reset and fill up ~half the cache.
    cache.clear();
    Cache.Entry entry = randomData(MAX_SIZE / 2 - getEntrySizeOnDisk("entry") - 1);
    cache.put("entry", entry);

    assertThatEntriesAreEqual(cache.get("entry"), entry);

    // Writing the large entry should no-op, because otherwise the pruning algorithm would clear
    // the whole cache, since the large entry is above the hysteresis threshold.
    cache.put("largeEntry", largeEntry);

    assertThat(cache.get("largeEntry"), is(nullValue()));
    assertThatEntriesAreEqual(cache.get("entry"), entry);
}
 
Example 5
Source File: RequestTools.java    From BigApp_WordPress_Android with Apache License 2.0 5 votes vote down vote up
/***
     * 緩存的數據
     *
     * @param response
     * @param maxAge        缓存的有效时间,默认60秒
     * @param oldSoftExpire
     * @return
     */
    private Cache.Entry cache(NetworkResponse response, long maxAge, long oldSoftExpire) {
        long now = System.currentTimeMillis();
        if (maxAge == 0) maxAge = CACHE_MAXAGE;
//        (如果判断服务器是用的缓存的,还是从网络上获取的呢,当前时间与之前记录的时间对比?如果大于60秒则表示是新的么?可以有)
        long softExpire = now + maxAge * 1000;
        Log.e("", "wenjun request cache() oldSoftExpire - now = " + (oldSoftExpire - now) + ", oldSoftExpire = " + oldSoftExpire + ", softExpire = " + softExpire);
        if ((oldSoftExpire > now) && (oldSoftExpire < softExpire)) {
            //如果之前的时间一定大于现在的时间,并且之前的时间减去现在的时间如果在60秒内,则表示是同一个,不用再更新缓存了
            return null;
        }

        Map<String, String> headers = response.headers;

        long serverDate = 0;
        String serverEtag = null;
        String headerValue;

        headerValue = headers.get("Date");
        if (headerValue != null) {
            serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
        }
        Cache.Entry entry = new Cache.Entry();
        entry.data = response.data;
        entry.etag = serverEtag;
        entry.softTtl = softExpire;
        entry.ttl = entry.softTtl;
        entry.serverDate = serverDate;
        entry.responseHeaders = headers;
        return entry;
    }
 
Example 6
Source File: DiskBasedCacheTest.java    From volley with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutClearGet() {
    Cache.Entry entry = randomData(511);
    cache.put("key", entry);

    assertThatEntriesAreEqual(cache.get("key"), entry);

    cache.clear();
    assertThat(cache.get("key"), is(nullValue()));
    assertThat(listCachedFiles(), is(emptyArray()));
}
 
Example 7
Source File: HttpHeaderParserTest.java    From product-emm with Apache License 2.0 5 votes vote down vote up
@Test public void parseCacheHeaders_expiresInPast() {
    long now = System.currentTimeMillis();
    headers.put("Date", rfc1123Date(now));
    headers.put("Expires", rfc1123Date(now - ONE_HOUR_MILLIS));

    Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);

    assertNotNull(entry);
    assertNull(entry.etag);
    assertEqualsWithin(entry.serverDate, now, ONE_MINUTE_MILLIS);
    assertEquals(0, entry.ttl);
    assertEquals(0, entry.softTtl);
}
 
Example 8
Source File: CacheTestUtils.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
/**
 * Makes a random cache entry.
 *
 * @param data         Data to use, or null to use random data
 * @param isExpired    Whether the TTLs should be set such that this entry is expired
 * @param needsRefresh Whether the TTLs should be set such that this entry needs refresh
 */
public static Cache.Entry makeRandomCacheEntry(byte[] data, boolean isExpired, boolean needsRefresh) {
    Random random = new Random();
    Cache.Entry entry = new Cache.Entry();
    if (data != null) {
        entry.data = data;
    } else {
        entry.data = new byte[random.nextInt(1024)];
    }
    entry.etag = String.valueOf(random.nextLong());
    entry.serverDate = random.nextLong();
    entry.ttl = isExpired ? 0 : Long.MAX_VALUE;
    entry.softTtl = needsRefresh ? 0 : Long.MAX_VALUE;
    return entry;
}
 
Example 9
Source File: BasicNetwork.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
private void addCacheHeaders(Map<String, String> headers, Cache.Entry entry) {
    // If there's no cache entry, we're done.
    if (entry == null) {
        return;
    }

    if (entry.etag != null) {
        headers.put("If-None-Match", entry.etag);
    }

    if (entry.serverDate > 0) {
        Date refTime = new Date(entry.serverDate);
        headers.put("If-Modified-Since", DateUtils.formatDate(refTime));
    }
}
 
Example 10
Source File: RequestTools.java    From BigApp_WordPress_Android with Apache License 2.0 5 votes vote down vote up
private void forceExpireCache(String url) {
    Cache cache = BaseApplication.getInstance().getRequestQueue().getCache();
    Cache.Entry entry = cache.get(url);
    if (entry != null && entry.data != null && entry.data.length > 0) {
        if (!entry.isExpired()) {
            setOldCachInvalidWhenHasNewDatas(url);
        }
    }
}
 
Example 11
Source File: HttpHeaderParserTest.java    From product-emm with Apache License 2.0 5 votes vote down vote up
@Test public void parseCacheHeaders_noHeaders() {
    Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);

    assertNotNull(entry);
    assertNull(entry.etag);
    assertEquals(0, entry.serverDate);
    assertEquals(0, entry.lastModified);
    assertEquals(0, entry.ttl);
    assertEquals(0, entry.softTtl);
}
 
Example 12
Source File: CacheHeader.java    From volley with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a new CacheHeader object.
 *
 * @param key The key that identifies the cache entry
 * @param entry The cache entry.
 */
CacheHeader(String key, Cache.Entry entry) {
    this(
            key,
            entry.etag,
            entry.serverDate,
            entry.lastModified,
            entry.ttl,
            entry.softTtl,
            getAllResponseHeaders(entry));
}
 
Example 13
Source File: HttpHeaderParserTest.java    From CrossBow with Apache License 2.0 5 votes vote down vote up
@Test public void parseCacheHeaders_cacheControlNoCache() {
    long now = System.currentTimeMillis();
    headers.put("Date", rfc1123Date(now));
    headers.put("Expires", rfc1123Date(now + ONE_HOUR_MILLIS));
    headers.put("Cache-Control", "no-cache");

    Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);

    assertNull(entry);
}
 
Example 14
Source File: HttpHeaderParserTest.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
public void testParseCacheHeaders_cacheControlNoCache() {
    long now = System.currentTimeMillis();
    headers.put("Date", rfc1123Date(now));
    headers.put("Expires", rfc1123Date(now + ONE_HOUR_MILLIS));
    headers.put("Cache-Control", "no-cache");

    Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);

    assertNull(entry);
}
 
Example 15
Source File: HttpHeaderParserTest.java    From product-emm with Apache License 2.0 5 votes vote down vote up
@Test public void parseCacheHeaders_normalExpire() {
    long now = System.currentTimeMillis();
    headers.put("Date", rfc1123Date(now));
    headers.put("Last-Modified", rfc1123Date(now - ONE_DAY_MILLIS));
    headers.put("Expires", rfc1123Date(now + ONE_HOUR_MILLIS));

    Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);

    assertNotNull(entry);
    assertNull(entry.etag);
    assertEqualsWithin(entry.serverDate, now, ONE_MINUTE_MILLIS);
    assertEqualsWithin(entry.lastModified, (now - ONE_DAY_MILLIS), ONE_MINUTE_MILLIS);
    assertTrue(entry.softTtl >= (now + ONE_HOUR_MILLIS));
    assertTrue(entry.ttl == entry.softTtl);
}
 
Example 16
Source File: HttpHeaderParserTest.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
public void testParseCacheHeaders_serverRelative() {

        long now = System.currentTimeMillis();
        // Set "current" date as one hour in the future
        headers.put("Date", rfc1123Date(now + ONE_HOUR_MILLIS));
        // TTL four hours in the future, so should be three hours from now
        headers.put("Expires", rfc1123Date(now + 4 * ONE_HOUR_MILLIS));

        Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);

        assertEqualsWithin(now + 3 * ONE_HOUR_MILLIS, entry.ttl, ONE_MINUTE_MILLIS);
        assertEquals(entry.softTtl, entry.ttl);
    }
 
Example 17
Source File: HttpHeaderParserTest.java    From CrossBow with Apache License 2.0 5 votes vote down vote up
@Test public void parseCacheHeaders_normalExpire() {
    long now = System.currentTimeMillis();
    headers.put("Date", rfc1123Date(now));
    headers.put("Last-Modified", rfc1123Date(now - ONE_DAY_MILLIS));
    headers.put("Expires", rfc1123Date(now + ONE_HOUR_MILLIS));

    Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);

    assertNotNull(entry);
    assertNull(entry.etag);
    assertEqualsWithin(entry.serverDate, now, ONE_MINUTE_MILLIS);
    assertEqualsWithin(entry.lastModified, (now - ONE_DAY_MILLIS), ONE_MINUTE_MILLIS);
    assertTrue(entry.softTtl >= (now + ONE_HOUR_MILLIS));
    assertTrue(entry.ttl == entry.softTtl);
}
 
Example 18
Source File: CacheHeader.java    From volley with Apache License 2.0 5 votes vote down vote up
private static List<Header> getAllResponseHeaders(Cache.Entry entry) {
    // If the entry contains all the response headers, use that field directly.
    if (entry.allResponseHeaders != null) {
        return entry.allResponseHeaders;
    }

    // Legacy fallback - copy headers from the map.
    return HttpHeaderParser.toAllHeaderList(entry.responseHeaders);
}
 
Example 19
Source File: HttpHeaderParser.java    From android-project-wo2b with Apache License 2.0 4 votes vote down vote up
/**
 * Extracts a {@link Cache.Entry} from a {@link NetworkResponse}.
 *
 * @param response The network response to parse headers from
 * @return a cache entry for the given response, or null if the response is not cacheable.
 */
public static Cache.Entry parseCacheHeaders(NetworkResponse response) {
    long now = System.currentTimeMillis();

    Map<String, String> headers = response.headers;

    long serverDate = 0;
    long serverExpires = 0;
    long softExpire = 0;
    long maxAge = 0;
    boolean hasCacheControl = false;

    String serverEtag = null;
    String headerValue;

    headerValue = headers.get("Date");
    if (headerValue != null) {
        serverDate = parseDateAsEpoch(headerValue);
    }

    headerValue = headers.get("Cache-Control");
    if (headerValue != null) {
        hasCacheControl = true;
        String[] tokens = headerValue.split(",");
        for (int i = 0; i < tokens.length; i++) {
            String token = tokens[i].trim();
            if (token.equals("no-cache") || token.equals("no-store")) {
                return null;
            } else if (token.startsWith("max-age=")) {
                try {
                    maxAge = Long.parseLong(token.substring(8));
                } catch (Exception e) {
                }
            } else if (token.equals("must-revalidate") || token.equals("proxy-revalidate")) {
                maxAge = 0;
            }
        }
    }

    headerValue = headers.get("Expires");
    if (headerValue != null) {
        serverExpires = parseDateAsEpoch(headerValue);
    }

    serverEtag = headers.get("ETag");

    // Cache-Control takes precedence over an Expires header, even if both exist and Expires
    // is more restrictive.
    if (hasCacheControl) {
        softExpire = now + maxAge * 1000;
    } else if (serverDate > 0 && serverExpires >= serverDate) {
        // Default semantic for Expire header in HTTP specification is softExpire.
        softExpire = now + (serverExpires - serverDate);
    }

    Cache.Entry entry = new Cache.Entry();
    entry.data = response.data;
    entry.etag = serverEtag;
    entry.softTtl = softExpire;
    entry.ttl = entry.softTtl;
    entry.serverDate = serverDate;
    entry.responseHeaders = headers;

    return entry;
}
 
Example 20
Source File: CacheTestUtils.java    From android-discourse with Apache License 2.0 2 votes vote down vote up
/**
 * Like {@link #makeRandomCacheEntry(byte[], boolean, boolean)} but
 * defaults to an unexpired entry.
 */
public static Cache.Entry makeRandomCacheEntry(byte[] data) {
    return makeRandomCacheEntry(data, false, false);
}