View Javadoc

1   package com.atlassian.seraph.util;
2   
3   import java.util.Collection;
4   import java.util.Collections;
5   import java.util.Map;
6   
7   /**
8    * Caches the results of the {@link PathMapper}
9    */
10  public class CachedPathMapper extends PathMapper
11  {
12      private Map cacheMap;
13      private Map cacheAllMap;
14  
15      /**
16       * Creates a CachedPathMapper object that will use cacheMap to cache the results of the {@link #get(String)} calls
17       * and cacheAllMap to cache the results of the {@link #getAll(String)} class.
18       * 
19       * @param cacheMap
20       * @param cacheAllMap
21       */
22      public CachedPathMapper(Map cacheMap, Map cacheAllMap)
23      {
24          // Synchronize access to the map for multi-threaded access
25          this.cacheMap = Collections.synchronizedMap(cacheMap);
26          this.cacheAllMap = Collections.synchronizedMap(cacheAllMap);
27      }
28  
29      public String get(String path)
30      {
31          // Check the cache
32          String result = (String) cacheMap.get(path);
33          if (result != null)
34          {
35              // The result for this path is cached, return the value
36              return result;
37          }
38          // Get the result from PathMapper
39          result = super.get(path);
40          // Cache the result
41          cacheMap.put(path, result);
42          return result;
43      }
44  
45      public Collection getAll(String path)
46      {
47          Collection result = (Collection) cacheAllMap.get(path);
48          // Check the cache
49          if (result != null)
50          {
51              // The result for this key is cached, return the value
52              return result;
53          }
54          // Get the result from PathMapper
55          result = super.getAll(path);
56          // Cache the result
57          cacheAllMap.put(path, result);
58          return result;
59      }
60  
61      public void put(String key, String pattern)
62      {
63          cacheMap.remove(key);
64          cacheAllMap.remove(key);
65          // Let PathMapper update the patterns
66          super.put(key, pattern);
67      }
68  }