View Javadoc

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