View Javadoc
1   package com.atlassian.cache.vcache;
2   
3   import java.io.ByteArrayOutputStream;
4   import java.io.IOException;
5   import java.io.ObjectOutputStream;
6   import java.io.Serializable;
7   import java.util.Base64;
8   import java.util.UUID;
9   import javax.annotation.Nonnull;
10  import javax.annotation.Nullable;
11  
12  import com.atlassian.cache.CacheException;
13  
14  class Utils
15  {
16      @Nonnull
17      static String asString(@Nullable Object key)
18      {
19          if (key == null)
20          {
21              throw new CacheException("key cannot be null");
22          }
23  
24          if (key instanceof String)
25          {
26              return (String) key;
27          }
28  
29          if (key instanceof Serializable)
30          {
31              final ByteArrayOutputStream baos = new ByteArrayOutputStream();
32              try (ObjectOutputStream oos = new ObjectOutputStream(baos))
33              {
34                  oos.writeObject(key);
35              }
36              catch (IOException ioe)
37              {
38                  throw new CacheException("Unable to convert key to String using serialization", ioe);
39              }
40              return Base64.getEncoder().encodeToString(baos.toByteArray());
41          }
42  
43          throw new CacheException("Key of type " + key.getClass().getName() + " is not supported");
44      }
45  
46      @Nonnull
47      static Serializable asSerializable(Object value)
48      {
49          //noinspection ConstantConditions
50          if (value == null)
51          {
52              throw new CacheException("value cannot be null");
53          }
54  
55          if (value instanceof Serializable)
56          {
57              return (Serializable) value;
58          }
59  
60          throw new CacheException("Value of type " + value.getClass().getName() + " is not supported");
61      }
62  
63      @Nonnull
64      static String uniqueId()
65      {
66          return UUID.randomUUID().toString();
67      }
68  }