GRÜN: Erwartungen implementiert
[demos/kafka/training] / src / main / java / de / juplo / kafka / SumBusinessLogic.java
index cea533f..a767aea 100644 (file)
@@ -2,15 +2,59 @@ package de.juplo.kafka;
 
 import java.util.HashMap;
 import java.util.Map;
+import java.util.Optional;
 
 
 public class SumBusinessLogic
 {
+  private final Map<String, Long> state;
+
+
   public SumBusinessLogic()
   {
+    this(new HashMap<>());
+  }
+
+  public SumBusinessLogic(Map<String, Long> state)
+  {
+    this.state = state;
   }
 
+
   public synchronized void startSum(String user)
   {
+    if (state.containsKey(user))
+      throw new IllegalStateException("Sumation for " + user + " already in progress, state: " + state.get(user));
+
+    state.put(user, 0l);
+  }
+
+  public synchronized Optional<Long> getSum(String user)
+  {
+    return Optional.ofNullable(state.get(user));
+  }
+
+  public synchronized void addToSum(String user, Integer value)
+  {
+    if (!state.containsKey(user))
+      throw new IllegalStateException("No sumation for " + user + " in progress");
+    if (value == null || value < 1)
+      throw new IllegalArgumentException("Not a positive number: " + value);
+
+    long result = state.get(user) + value;
+    state.put(user, result);
+  }
+
+  public synchronized Long endSum(String user)
+  {
+    if (!state.containsKey(user))
+      throw new IllegalStateException("No sumation for " + user + " in progress");
+
+    return state.remove(user);
+  }
+
+  protected Map<String, Long> getState()
+  {
+    return state;
   }
 }