View Javadoc

1   package com.atlassian.httpclient.apache.httpcomponents.cache;
2   
3   import org.apache.http.client.cache.HttpCacheEntry;
4   import org.apache.http.client.cache.HttpCacheUpdateCallback;
5   import org.apache.http.impl.client.cache.CacheConfig;
6   
7   import java.io.IOException;
8   import java.util.Iterator;
9   import java.util.Map;
10  import java.util.regex.Pattern;
11  
12  /**
13   * Originally copied from {@link org.apache.http.impl.client.cache.BasicHttpCacheStorage} v4.1.2
14   * <p>
15   * Have added ability to flush cache
16   */
17  public final class FlushableHttpCacheStorageImpl implements FlushableHttpCacheStorage {
18      private final CacheMap entries;
19  
20      public FlushableHttpCacheStorageImpl(CacheConfig config) {
21          this.entries = new CacheMap(config.getMaxCacheEntries());
22      }
23  
24      @Override
25      public synchronized void flushByUriPattern(Pattern urlPattern) {
26          for (Iterator<Map.Entry<String, HttpCacheEntry>> i = entries.entrySet().iterator(); i.hasNext(); ) {
27              final Map.Entry<String, HttpCacheEntry> entry = i.next();
28              if (urlPattern.matcher(entry.getKey()).matches()) {
29                  i.remove();
30              }
31          }
32      }
33  
34      /**
35       * Places a HttpCacheEntry in the cache
36       *
37       * @param url   Url to use as the cache key
38       * @param entry HttpCacheEntry to place in the cache
39       */
40      public synchronized void putEntry(String url, HttpCacheEntry entry) throws IOException {
41          entries.put(url, entry);
42      }
43  
44      /**
45       * Gets an entry from the cache, if it exists
46       *
47       * @param url Url that is the cache key
48       * @return HttpCacheEntry if one exists, or null for cache miss
49       */
50      public synchronized HttpCacheEntry getEntry(String url) {
51          return entries.get(url);
52      }
53  
54      /**
55       * Removes a HttpCacheEntry from the cache
56       *
57       * @param url Url that is the cache key
58       */
59      public synchronized void removeEntry(String url) throws IOException {
60          entries.remove(url);
61      }
62  
63      public synchronized void updateEntry(String url, HttpCacheUpdateCallback callback) throws IOException {
64          HttpCacheEntry existingEntry = entries.get(url);
65          entries.put(url, callback.update(existingEntry));
66      }
67  }