Die App führt die Berechnung aus
[demos/kafka/training] / src / main / java / de / juplo / kafka / AdderBusinessLogic.java
diff --git a/src/main/java/de/juplo/kafka/AdderBusinessLogic.java b/src/main/java/de/juplo/kafka/AdderBusinessLogic.java
new file mode 100644 (file)
index 0000000..c0c19a5
--- /dev/null
@@ -0,0 +1,50 @@
+package de.juplo.kafka;
+
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+
+
+public class AdderBusinessLogic
+{
+  private final Map<String, AdderResult> state;
+
+
+  public AdderBusinessLogic()
+  {
+    this(new HashMap<>());
+  }
+
+  public AdderBusinessLogic(Map<String, AdderResult> state)
+  {
+    this.state = state;
+  }
+
+
+  public synchronized Optional<Long> getSum(String user)
+  {
+    return Optional.ofNullable(state.get(user)).map(result -> result.sum);
+  }
+
+  public synchronized void addToSum(String user, Integer value)
+  {
+    if (value == null || value < 1)
+      throw new IllegalArgumentException("Not a positive number: " + value);
+
+    long sum =
+        Optional
+            .ofNullable(state.get(user))
+            .map(result -> result.sum)
+            .orElse(0l);
+    state.put(user, new AdderResult(value, sum + value));
+  }
+
+  public synchronized AdderResult calculate(String user)
+  {
+    if (!state.containsKey(user))
+      throw new IllegalStateException("No sumation for " + user + " in progress");
+
+    return state.remove(user);
+  }
+}