|
3 | 3 | import com.fasterxml.jackson.core.JsonProcessingException;
|
4 | 4 | import com.fasterxml.jackson.databind.ObjectMapper;
|
5 | 5 | import io.fabric8.kubernetes.client.CustomResource;
|
6 |
| -import java.util.Map; |
7 | 6 | import java.util.Optional;
|
8 | 7 | import java.util.concurrent.ConcurrentHashMap;
|
| 8 | +import java.util.concurrent.ConcurrentMap; |
9 | 9 | import java.util.concurrent.locks.Lock;
|
10 | 10 | import java.util.concurrent.locks.ReentrantLock;
|
11 | 11 | import java.util.function.Predicate;
|
12 | 12 | import org.slf4j.Logger;
|
13 | 13 | import org.slf4j.LoggerFactory;
|
14 | 14 |
|
| 15 | +@SuppressWarnings("rawtypes") |
15 | 16 | public class CustomResourceCache {
|
16 | 17 |
|
17 | 18 | private static final Logger log = LoggerFactory.getLogger(CustomResourceCache.class);
|
18 | 19 |
|
19 |
| - private ObjectMapper objectMapper = new ObjectMapper(); |
20 |
| - private final Map<String, CustomResource> resources = new ConcurrentHashMap<>(); |
| 20 | + private final ObjectMapper objectMapper; |
| 21 | + private final ConcurrentMap<String, CustomResource> resources = new ConcurrentHashMap<>(); |
21 | 22 | private final Lock lock = new ReentrantLock();
|
22 | 23 |
|
| 24 | + public CustomResourceCache() { |
| 25 | + this(new ObjectMapper()); |
| 26 | + } |
| 27 | + |
| 28 | + public CustomResourceCache(ObjectMapper objectMapper) { |
| 29 | + this.objectMapper = objectMapper; |
| 30 | + } |
| 31 | + |
23 | 32 | public void cacheResource(CustomResource resource) {
|
24 | 33 | try {
|
25 | 34 | lock.lock();
|
@@ -49,18 +58,13 @@ public void cacheResource(CustomResource resource, Predicate<CustomResource> pre
|
49 | 58 | * @return
|
50 | 59 | */
|
51 | 60 | public Optional<CustomResource> getLatestResource(String uuid) {
|
52 |
| - return Optional.ofNullable(clone(resources.get(uuid))); |
| 61 | + return Optional.ofNullable(resources.get(uuid)).map(this::clone); |
53 | 62 | }
|
54 | 63 |
|
55 | 64 | private CustomResource clone(CustomResource customResource) {
|
56 | 65 | try {
|
57 |
| - if (customResource == null) { |
58 |
| - return null; |
59 |
| - } |
60 |
| - CustomResource clonedObject = |
61 |
| - objectMapper.readValue( |
62 |
| - objectMapper.writeValueAsString(customResource), customResource.getClass()); |
63 |
| - return clonedObject; |
| 66 | + return objectMapper.readValue( |
| 67 | + objectMapper.writeValueAsString(customResource), customResource.getClass()); |
64 | 68 | } catch (JsonProcessingException e) {
|
65 | 69 | throw new IllegalStateException(e);
|
66 | 70 | }
|
|
0 commit comments