Verbesserte Tests und Korrekturen gemerged: stored-offsets -> stored-state
[demos/kafka/training] / src / main / java / de / juplo / kafka / ApplicationRecordHandler.java
diff --git a/src/main/java/de/juplo/kafka/ApplicationRecordHandler.java b/src/main/java/de/juplo/kafka/ApplicationRecordHandler.java
new file mode 100644 (file)
index 0000000..c2c2657
--- /dev/null
@@ -0,0 +1,46 @@
+package de.juplo.kafka;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+
+import java.util.HashMap;
+import java.util.Map;
+
+
+@Slf4j
+public class ApplicationRecordHandler implements RecordHandler<String, Long>
+{
+  private final Map<Integer, Map<String, Long>> state = new HashMap<>();
+
+
+  @Override
+  public void accept(ConsumerRecord<String, Long> record)
+  {
+    Integer partition = record.partition();
+    String key = record.key() == null ? "NULL" : record.key().toString();
+    Map<String, Long> byKey = state.get(partition);
+
+    if (!byKey.containsKey(key))
+      byKey.put(key, 0l);
+
+    long seenByKey = byKey.get(key);
+    seenByKey++;
+    byKey.put(key, seenByKey);
+  }
+
+  protected void addPartition(Integer partition, Map<String, Long> state)
+  {
+    this.state.put(partition, state);
+  }
+
+  protected Map<String, Long> removePartition(Integer partition)
+  {
+    return this.state.remove(partition);
+  }
+
+
+  public Map<Integer, Map<String, Long>> getState()
+  {
+    return state;
+  }
+}