1   package com.atlassian.core.filters.cache;
2   
3   import com.atlassian.core.filters.AbstractHttpFilter;
4   
5   import javax.servlet.FilterChain;
6   import javax.servlet.ServletException;
7   import javax.servlet.FilterConfig;
8   import javax.servlet.http.HttpServletResponse;
9   import javax.servlet.http.HttpServletRequest;
10  import java.io.IOException;
11  
12  /**
13   * Uses a list of caching strategies provided by the subclass, applying the first one which matches.
14   * After the caching headers are applied (or not, if no strategies match), the request is processed
15   * as normal.
16   *
17   * @see CachingStrategy
18   * @since 4.0
19   */
20  public abstract class AbstractCachingFilter extends AbstractHttpFilter
21  {
22      /**
23       * Before processing the filter chain, iterates through the caching strategies returned by
24       * {@link #getCachingStrategies()} and applies the first one that matches.
25       */
26      public final void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
27          throws IOException, ServletException
28      {
29          CachingStrategy strategy = getFirstMatchingStrategy(request);
30          if (strategy != null)
31              strategy.setCachingHeaders(response);
32  
33          filterChain.doFilter(request, response);
34      }
35  
36      private CachingStrategy getFirstMatchingStrategy(HttpServletRequest request)
37      {
38          CachingStrategy[] strategies = getCachingStrategies();
39          if (strategies == null)
40              return null;
41  
42          for (CachingStrategy strategy : strategies)
43          {
44              if (strategy.matches(request))
45                  return strategy;
46          }
47          return null;
48      }
49  
50      /**
51       * Subclasses should return an array of caching strategies to use. The first one that matches
52       * will be applied by this filter.
53       */
54      abstract protected CachingStrategy[] getCachingStrategies();
55  
56  
57      // not to be overridden
58      public final void init(FilterConfig filterConfig) throws ServletException
59      {
60          super.init(filterConfig);
61      }
62  
63      // not to be overridden
64      public final void destroy()
65      {
66          super.destroy();
67      }
68  }