View Javadoc
1   package com.atlassian.plugin.servlet;
2   
3   import javax.servlet.http.HttpServletRequest;
4   import javax.servlet.http.HttpServletResponse;
5   
6   public class ResourceDownloadUtils {
7       private static final long ONE_YEAR_SECONDS = 60L * 60L * 24L * 365L;
8       private static final long ONE_YEAR_MILLISECONDS = 1000 * ONE_YEAR_SECONDS;
9   
10      /**
11       * Set 'expire' headers to cache for one year. Also adds the additional cache control values passed in.
12       * Note, this method resets the cache control headers if set previously.
13       *
14       * If caches are disabled (via the system property atlassian.disable.caches), this method sets 'expires' to 0.
15       */
16      public static void addCachingHeaders(HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse, final String... cacheControls) {
17          boolean cacheDisabledByQueryParam = "false".equals(httpServletRequest.getParameter("cache"));
18          if (Boolean.getBoolean("atlassian.disable.caches")) {
19              httpServletResponse.setDateHeader("Expires", 0);
20              httpServletResponse.setHeader("Cache-Control", "no-cache, must-revalidate");
21          } else if (!cacheDisabledByQueryParam) {
22              httpServletResponse.setDateHeader("Expires", System.currentTimeMillis() + ONE_YEAR_MILLISECONDS);
23              httpServletResponse.setHeader("Cache-Control", "max-age=" + ONE_YEAR_SECONDS);
24              for (final String cacheControl : cacheControls) {
25                  httpServletResponse.addHeader("Cache-Control", cacheControl);
26              }
27          }
28      }
29  
30      /**
31       * Sets caching headers with public cache control. Applications should call this method from urlrewrite.xml to
32       * decorate urls like <code>/s/{build num}/.../_/resourceurl</code>.
33       *
34       * @see <a href="http://tuckey.org/urlrewrite/manual/2.6/">http://tuckey.org/urlrewrite/manual/2.6/</a>
35       */
36      public static void addPublicCachingHeaders(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) {
37          addCachingHeaders(httpServletRequest, httpServletResponse, "public");
38      }
39  
40      /**
41       * Sets caching headers with private cache control. Applications should call this method from urlrewrite.xml to
42       * decorate urls like <code>/sp/{build num}/.../_/resourceurl</code>.
43       *
44       * @see <a href="http://tuckey.org/urlrewrite/manual/2.6/">http://tuckey.org/urlrewrite/manual/2.6/</a>
45       */
46      public static void addPrivateCachingHeaders(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) {
47          addCachingHeaders(httpServletRequest, httpServletResponse, "private");
48      }
49  }