1 package com.atlassian.vcache.internal.core.cas;
2
3 import com.atlassian.marshalling.api.MarshallingException;
4 import com.atlassian.marshalling.api.MarshallingPair;
5 import com.atlassian.vcache.CasIdentifier;
6 import com.atlassian.vcache.ExternalCacheException;
7 import com.atlassian.vcache.IdentifiedValue;
8 import com.atlassian.vcache.internal.core.DefaultIdentifiedValue;
9 import org.slf4j.Logger;
10 import org.slf4j.LoggerFactory;
11
12 import javax.annotation.Nullable;
13 import java.io.Serializable;
14 import java.util.Optional;
15
16 import static com.atlassian.vcache.ExternalCacheException.Reason.MARSHALLER_FAILURE;
17 import static com.atlassian.vcache.ExternalCacheException.Reason.UNCLASSIFIED_FAILURE;
18 import static java.util.Objects.requireNonNull;
19
20
21
22
23
24
25 public class IdentifiedUtils {
26 private static final Logger log = LoggerFactory.getLogger(IdentifiedUtils.class);
27
28 public static <V> IdentifiedData marshall(V data, Optional<MarshallingPair<V>> valueMarshalling) throws ExternalCacheException {
29 requireNonNull(data);
30 try {
31 return valueMarshalling.isPresent()
32 ? new IdentifiedDataBytes(valueMarshalling.get().getMarshaller().marshallToBytes(data))
33 : new IdentifiedDataSerializable((Serializable) data);
34 } catch (MarshallingException e) {
35 throw new ExternalCacheException(MARSHALLER_FAILURE, e);
36 }
37 }
38
39 @SuppressWarnings("unchecked")
40 public static <V> Optional<V> unmarshall(@Nullable IdentifiedData idata, Optional<MarshallingPair<V>> valueMarshalling)
41 throws ExternalCacheException {
42 if (idata == null) {
43 return Optional.empty();
44 }
45
46 try {
47 return valueMarshalling.isPresent()
48 ? Optional.of(valueMarshalling.get().getUnmarshaller().unmarshallFrom(((IdentifiedDataBytes) idata).getBytes()))
49 : Optional.of((V) ((IdentifiedDataSerializable) idata).getObject());
50 } catch (MarshallingException ex) {
51 throw new ExternalCacheException(MARSHALLER_FAILURE, ex);
52 }
53 }
54
55 @SuppressWarnings("unchecked")
56 public static <V> Optional<IdentifiedValue<V>> unmarshallIdentified(
57 @Nullable IdentifiedData idata, Optional<MarshallingPair<V>> valueMarshalling) {
58 if (idata == null) {
59 return Optional.empty();
60 }
61
62 try {
63 final V value = valueMarshalling.isPresent()
64 ? valueMarshalling.get().getUnmarshaller().unmarshallFrom(((IdentifiedDataBytes) idata).getBytes())
65 : (V) ((IdentifiedDataSerializable) idata).getObject();
66 return Optional.of(new DefaultIdentifiedValue<>(idata, value));
67 } catch (MarshallingException ex) {
68 throw new ExternalCacheException(MARSHALLER_FAILURE, ex);
69 }
70 }
71
72 public static IdentifiedData safeCast(CasIdentifier casId) {
73 if (casId instanceof IdentifiedData) {
74 return (IdentifiedData) casId;
75 }
76
77 log.warn("Passed an unknown CasIdentifier instance of class {}.", casId.getClass().getName());
78 throw new ExternalCacheException(UNCLASSIFIED_FAILURE);
79 }
80 }