View Javadoc

1   package com.atlassian.gzipfilter.selector;
2   
3   import java.util.regex.Pattern;
4   import java.util.Map;
5   import java.util.Collections;
6   import java.util.HashMap;
7   
8   /**
9    * This class may be called by multiple threads - it is internally synchronised.
10   */
11  public class PatternMatcher
12  {
13      // Although synchronisation here may be a point of contention,
14      // when running with 20 threads, uncached gives a performance time of
15      // 27 seconds.  Cached gives 13 seconds.
16      // The performance test can be found in TestPatternMatcher
17      private final Map patternCache = Collections.synchronizedMap(new HashMap());
18  
19      /**
20       * @param contentType     The content type to match
21       * @param mimeTypesToGzip A comma separated list of regular expressions to match against
22       * @return True if the content type matches a least one of the regular expressions
23       */
24      public boolean matches(String contentType, String mimeTypesToGzip)
25      {
26          final String[] mimeTypes = mimeTypesToGzip.split(",");
27  
28          for (int i = 0; i < mimeTypes.length; i++)
29          {
30              String mimeType = mimeTypes[i].trim();
31              Pattern p = (Pattern) patternCache.get(mimeType);
32              if (p == null)
33              {
34                  p = Pattern.compile(mimeType);
35                  patternCache.put(mimeType, p);
36              }
37  
38              if (p.matcher(contentType).matches())
39              {
40                  return true;
41              }
42          }
43          return false;
44      }
45  
46  }