View Javadoc

1   package com.atlassian.vcache.internal.core;
2   
3   import javax.annotation.Nonnull;
4   
5   import org.slf4j.Logger;
6   import org.slf4j.LoggerFactory;
7   
8   import static com.atlassian.vcache.internal.NameValidator.requireValidProductIdentifier;
9   
10  /**
11   * Represents the ability to generate the keys used with an external cache.
12   */
13  public abstract class ExternalCacheKeyGenerator
14  {
15      private static final Logger log = LoggerFactory.getLogger(ExternalCacheKeyGenerator.class);
16  
17      private static final String SEPARATOR = "::";
18      private static final String CACHE_VERSION_KEY = "cache-version";
19  
20      private final String productIdentifier;
21  
22      public ExternalCacheKeyGenerator(String productIdentifier)
23      {
24          this.productIdentifier = requireValidProductIdentifier(productIdentifier);
25      }
26  
27      /**
28       * Generates the key for an individual entry.
29       */
30      @Nonnull
31      public String entryKey(String partition, String cacheName, long cacheVersion, String entryKey)
32      {
33          final String plain = productIdentifier + SEPARATOR + partition + SEPARATOR + cacheName
34                  + SEPARATOR + cacheVersion + SEPARATOR + entryKey;
35          final String encoded = encode(plain);
36          log.trace("Encoded cacheKey {} to {}", plain, encoded);
37          return encoded;
38      }
39  
40      /**
41       * Generates the key used to hold the cache version number.
42       */
43      @Nonnull
44      public String cacheVersionKey(String partition, String cacheName)
45      {
46          final String plain = productIdentifier + SEPARATOR + partition + SEPARATOR + cacheName
47                  + SEPARATOR + CACHE_VERSION_KEY;
48          final String encoded = encode(plain);
49          log.trace("Encoded cacheVersionKey {} to {}", plain, encoded);
50          return encoded;
51      }
52  
53      /**
54       * Responsible for encoding the plain key using the appropriate algorithm.
55       * @param plain the plain key to be encoded
56       * @return the key encoded
57       */
58      @Nonnull
59      protected abstract String encode(String plain);
60  }