|
| 1 | +package com.fingerprint.v4.sdk; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.annotation.JsonTypeInfo; |
| 4 | +import com.fasterxml.jackson.core.JsonParser; |
| 5 | +import com.fasterxml.jackson.databind.DeserializationContext; |
| 6 | +import com.fasterxml.jackson.databind.JsonDeserializer; |
| 7 | +import com.fasterxml.jackson.databind.JsonMappingException; |
| 8 | +import com.fasterxml.jackson.databind.JsonNode; |
| 9 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 10 | +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; |
| 11 | +import com.fasterxml.jackson.databind.node.ObjectNode; |
| 12 | +import com.fingerprint.v4.model.Event; |
| 13 | +import com.fingerprint.v4.model.EventDevice; |
| 14 | +import com.fingerprint.v4.model.EventEdge; |
| 15 | +import java.io.IOException; |
| 16 | + |
| 17 | +/** |
| 18 | + * Treats a missing, null, or empty Event {@code source} as {@code device}. |
| 19 | + * Unknown non-empty values fail. Never rewrites {@code edge}. |
| 20 | + */ |
| 21 | +public final class EventDeserializer extends JsonDeserializer<Event> { |
| 22 | + @Override |
| 23 | + public Event deserialize(JsonParser parser, DeserializationContext context) throws IOException { |
| 24 | + JsonNode node = parser.getCodec().readTree(parser); |
| 25 | + if (node == null || !node.isObject()) { |
| 26 | + throw JsonMappingException.from(parser, "event JSON must be an object"); |
| 27 | + } |
| 28 | + |
| 29 | + ObjectNode object = (ObjectNode) node; |
| 30 | + JsonNode source = object.get("source"); |
| 31 | + if (source == null || source.isNull() || (source.isTextual() && source.asText().isEmpty())) { |
| 32 | + object.put("source", "device"); |
| 33 | + source = object.get("source"); |
| 34 | + } |
| 35 | + |
| 36 | + if (!source.isTextual()) { |
| 37 | + throw JsonMappingException.from(parser, "unknown Event source: " + source); |
| 38 | + } |
| 39 | + |
| 40 | + String value = source.asText(); |
| 41 | + ObjectMapper implMapper = ((ObjectMapper) parser.getCodec()).copy(); |
| 42 | + implMapper.addMixIn(Event.class, StripEventPolymorphism.class); |
| 43 | + if ("device".equals(value)) { |
| 44 | + return implMapper.treeToValue(object, EventDevice.class); |
| 45 | + } |
| 46 | + if ("edge".equals(value)) { |
| 47 | + return implMapper.treeToValue(object, EventEdge.class); |
| 48 | + } |
| 49 | + throw JsonMappingException.from(parser, "unknown Event source: " + value); |
| 50 | + } |
| 51 | + |
| 52 | + @JsonTypeInfo(use = JsonTypeInfo.Id.NONE) |
| 53 | + @JsonDeserialize(using = JsonDeserializer.None.class) |
| 54 | + abstract static class StripEventPolymorphism {} |
| 55 | +} |
0 commit comments