Der Test verwendet die `@Bean` von `EndlessConsumer`
[demos/kafka/training] / src / main / java / de / juplo / kafka / AdderBusinessLogic.java
index 9fd5b0d..d525182 100644 (file)
@@ -8,7 +8,7 @@ import java.util.Optional;
 
 public class AdderBusinessLogic
 {
-  private final Map<String, Long> state;
+  private final Map<String, AdderResult> state;
 
 
   public AdderBusinessLogic()
@@ -16,22 +16,40 @@ public class AdderBusinessLogic
     this(new HashMap<>());
   }
 
-  public AdderBusinessLogic(Map<String, Long> state)
+  public AdderBusinessLogic(Map<String, AdderResult> state)
   {
     this.state = state;
   }
 
 
-  public synchronized void startSum(String user)
+  public synchronized Optional<Long> getSum(String user)
   {
-    if (state.containsKey(user))
-      throw new IllegalStateException("Sumation for " + user + " already in progress, state: " + state.get(user));
+    return Optional.ofNullable(state.get(user)).map(result -> result.sum);
+  }
 
-    state.put(user, 0l);
+  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 Optional<Long> getSum(String user)
+  public synchronized AdderResult calculate(String user)
+  {
+    if (!state.containsKey(user))
+      throw new IllegalStateException("No sumation for " + user + " in progress");
+
+    return state.remove(user);
+  }
+
+  protected Map<String, AdderResult> getState()
   {
-    return Optional.ofNullable(state.get(user));
+    return state;
   }
 }