All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.serialized.client.aggregate.EventDeserializer Maven / Gradle / Ivy

The newest version!
package io.serialized.client.aggregate;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

import static io.serialized.client.aggregate.Event.newEvent;

class EventDeserializer extends StdDeserializer> {

  private final Map eventTypes;

  private EventDeserializer(Map eventTypes) {
    super((Class) null);
    this.eventTypes = eventTypes;
  }

  static Module module(Map eventTypes) {
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Event.class, new EventDeserializer(eventTypes));
    return module;
  }

  @Override
  public Event deserialize(JsonParser jp, DeserializationContext context) throws IOException {
    JsonNode node = jp.getCodec().readTree(jp);
    String eventId = node.get("eventId").asText();
    String eventType = node.get("eventType").asText();
    Optional encryptedData = Optional.ofNullable(node.get("encryptedData"));

    Optional matchingClass = eventTypes
        .entrySet()
        .stream()
        .filter(et -> et.getKey().equals(eventType))
        .map(Map.Entry::getValue)
        .findFirst();

    JsonNode data = node.get("data");
    if (matchingClass.isPresent()) {
      Event.TypedBuilder eventBuilder = newEvent(matchingClass.get()).eventId(UUID.fromString(eventId));
      eventBuilder.data(jp.getCodec().treeToValue(data, matchingClass.get()));
      encryptedData.ifPresent(encData -> eventBuilder.encryptedData(encData.asText()));
      return eventBuilder.build();
    } else {
      Event.RawBuilder eventBuilder = newEvent(eventType).eventId(UUID.fromString(eventId));
      eventBuilder.data(jp.getCodec().treeToValue(data, Map.class));
      encryptedData.ifPresent(encData -> eventBuilder.encryptedData(encData.asText()));
      return eventBuilder.build();
    }

  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy