package io.quarkus.kafka.client.serialization;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.json.bind.Jsonb;

import org.apache.kafka.common.serialization.Deserializer;

/**
 * A {@link Deserializer} that deserializes JSON using JSON-B.
 */
public class JsonbDeserializer<T> implements Deserializer<T> {

    private final Jsonb jsonb;
    private final Class<T> type;
    private final boolean jsonbNeedsClosing;

    public JsonbDeserializer(Class<T> type) {
        this(type, JsonbProducer.get(), true);
    }

    public JsonbDeserializer(Class<T> type, Jsonb jsonb) {
        this(type, jsonb, false);
    }

    private JsonbDeserializer(Class<T> type, Jsonb jsonb, boolean jsonbNeedsClosing) {
        this.type = type;
        this.jsonb = jsonb;
        this.jsonbNeedsClosing = jsonbNeedsClosing;
    }

    @Override
    public void configure(Map<String, ?> configs, boolean isKey) {
    }

    @Override
    public T deserialize(String topic, byte[] data) {
        if (data == null) {
            return null;
        }

        try (InputStream is = new ByteArrayInputStream(data)) {
            return jsonb.fromJson(is, type);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void close() {
        if (!jsonbNeedsClosing) {
            return;
        }

        try {
            jsonb.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

@@ -126,32 +126,63 @@
 io.InputStream;%0A
+import java.lang.reflect.Type;%0A
 import java.util
@@ -463,24 +463,20 @@
 e final 
-Class%3CT%3E
+Type
  type;%0A 
@@ -553,24 +553,426 @@
 zer(Class%3CT%3E
+ clazz) %7B%0A        this(clazz, JsonbProducer.get(), true);%0A    %7D%0A%0A    public JsonbDeserializer(Class%3CT%3E clazz, Jsonb jsonb) %7B%0A        this(clazz, jsonb, false);%0A    %7D%0A%0A    private JsonbDeserializer(Class%3CT%3E clazz, Jsonb jsonb, boolean jsonbNeedsClosing) %7B%0A        this.type = clazz;%0A        this.jsonb = jsonb;%0A        this.jsonbNeedsClosing = jsonbNeedsClosing;%0A    %7D%0A%0A    public JsonbDeserializer(Type
  type) %7B%0A   
@@ -1047,32 +1047,28 @@
 eserializer(
-Class%3CT%3E
+Type
  type, Jsonb
@@ -1148,24 +1148,20 @@
 ializer(
-Class%3CT%3E
+Type
  type, J

Allow JsonbDeserializer based on generic types