View Javadoc

1   package com.atlassian.plugin.webresource.cache;
2   
3   import com.atlassian.plugin.cache.filecache.FileCache;
4   import com.atlassian.plugin.cache.filecache.FileCacheStreamProvider;
5   import com.atlassian.plugin.servlet.DownloadException;
6   import com.atlassian.plugin.webresource.ResourceUtils;
7   
8   import java.io.OutputStream;
9   import java.util.Map;
10  import java.util.TreeMap;
11  
12  /**
13   * A small facarde around a FileCacheStreamProvider, that captures both the cache key
14   * and FileCache, saving having to pass them around seperately
15   *
16   * @since v2.13
17   */
18  public interface CacheHandle {
19      void stream(OutputStream out, FileCacheStreamProvider streamProvider) throws DownloadException;
20  
21      public static class Builder {
22          /** does not cache, calls the stream provider directly */
23          public static CacheHandle passthrough() {
24              return new CacheHandle() {
25                  @Override
26                  public void stream(OutputStream out, FileCacheStreamProvider streamProvider) throws DownloadException {
27                      streamProvider.writeStream(out);
28                  }
29              };
30          }
31  
32          /**
33           * inspects the request, and if appropriate, returns a CacheHandle that will
34           * cache resources to the cache.
35           * If not approriate, a passthrough() handle is returned.
36           */
37          public static CacheHandle forRequest(final FileCache<FileCacheKey> cache, String downloadtype, String path, final Map<String, String> params)
38          {
39              if (!ResourceUtils.canRequestedResourcesContentBeAssumedConstant(params))
40              {
41                  return passthrough();
42              }
43  
44              final FileCacheKey cacheKey = new FileCacheKey(new TreeMap<String, String>(params), downloadtype, path);
45              return new CacheHandle() {
46                  @Override
47                  public void stream(OutputStream out, FileCacheStreamProvider streamProvider) throws DownloadException {
48                      cache.stream(cacheKey, out, streamProvider);
49                  }
50              };
51          }
52  
53      }
54  
55  }