1 package com.atlassian.vcache.internal.guava;
2
3 import com.atlassian.marshalling.api.MarshallingPair;
4 import com.atlassian.vcache.ExternalCacheException;
5 import com.atlassian.vcache.ExternalCacheSettings;
6 import com.atlassian.vcache.PutPolicy;
7 import com.atlassian.vcache.internal.core.cas.IdentifiedData;
8 import com.atlassian.vcache.internal.core.cas.IdentifiedUtils;
9 import com.google.common.cache.Cache;
10 import com.google.common.cache.CacheBuilder;
11
12 import java.util.Map;
13 import java.util.Objects;
14 import java.util.Optional;
15 import java.util.Set;
16 import java.util.concurrent.TimeUnit;
17 import java.util.stream.Collectors;
18 import java.util.stream.StreamSupport;
19
20
21
22
23
24
25 public class GuavaUtils {
26
27 static boolean directPut(
28 String externalKey,
29 IdentifiedData identifiedData,
30 PutPolicy policy,
31 Cache<String, IdentifiedData> delegate) {
32
33 switch (policy) {
34 case ADD_ONLY:
35 return delegate.asMap().putIfAbsent(externalKey, identifiedData) == null;
36
37 case PUT_ALWAYS:
38 delegate.put(externalKey, identifiedData);
39 return true;
40
41 case REPLACE_ONLY:
42 final IdentifiedData existingData = delegate.getIfPresent(externalKey);
43 return (existingData != null) && delegate.asMap().replace(externalKey, existingData, identifiedData);
44
45 default:
46 throw new IllegalArgumentException("Unknown put policy: " + policy);
47 }
48 }
49
50 static ExternalCacheException mapException(Exception ex) {
51 return new ExternalCacheException(ExternalCacheException.Reason.UNCLASSIFIED_FAILURE, ex);
52 }
53
54 static <V> Map<String, Optional<V>> directGetBulk(
55 Set<String> externalKeys, Cache<String, IdentifiedData> delegate, Optional<MarshallingPair<V>> valueMarshalling) {
56 return StreamSupport.stream(externalKeys.spliterator(), false)
57 .distinct()
58 .collect(Collectors.toMap(
59 Objects::requireNonNull,
60 k -> IdentifiedUtils.unmarshall(delegate.getIfPresent(k), valueMarshalling)));
61 }
62
63 public static Cache<String, IdentifiedData> buildDelegate(ExternalCacheSettings settings) {
64
65 return CacheBuilder.newBuilder()
66 .maximumSize(settings.getEntryCountHint().get())
67 .expireAfterWrite(settings.getDefaultTtl().get().toMillis(), TimeUnit.MILLISECONDS)
68 .build();
69 }
70 }