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

io.keyko.monitoring.serde.JsonPOJOSerde Maven / Gradle / Ivy

package io.keyko.monitoring.serde;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.kafka.common.errors.SerializationException;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serializer;

import java.util.Map;


public class JsonPOJOSerde implements Serde {

  private final ObjectMapper mapper = new ObjectMapper();
  private final Class cls;

  public JsonPOJOSerde(Class cls) {
    this.cls = cls;
  }

  @Override
  public void configure(Map configs, boolean isKey) {

  }

  @Override
  public void close() {

  }

  @Override
  public Serializer serializer() {
    return new Serializer() {

      @Override
      public void configure(Map configs, boolean isKey) {

      }

      @Override
      public byte[] serialize(String topic, T data) {
        try {
          return mapper.writeValueAsBytes(data);
        } catch (Exception e) {
          throw new SerializationException("Error serializing JSON message", e);
        }
      }

      @Override
      public void close() {

      }
    };

  }

  @Override
  public Deserializer deserializer() {
    return new Deserializer() {
      @Override
      public void configure(Map configs, boolean isKey) {

      }

      @Override
      public T deserialize(String topic, byte[] data) {
        T result;

        if (data == null) {
          //  System.out.println("Null data for topic: " + topic);
          return null;
        }

        try {
          result = mapper.readValue(data, cls);
        } catch (Exception e) {
          throw new SerializationException(e);
        }

        return result;
      }

      @Override
      public void close() {

      }
    };
  }
}





© 2015 - 2025 Weber Informatics LLC | Privacy Policy