GRÜN: Erwartungen implementiert
[demos/kafka/training] / src / main / java / de / juplo / kafka / SumBusinessLogic.java
1 package de.juplo.kafka;
2
3 import java.util.HashMap;
4 import java.util.Map;
5 import java.util.Optional;
6
7
8 public class SumBusinessLogic
9 {
10   private final Map<String, Long> state;
11
12
13   public SumBusinessLogic()
14   {
15     this(new HashMap<>());
16   }
17
18   public SumBusinessLogic(Map<String, Long> state)
19   {
20     this.state = state;
21   }
22
23
24   public synchronized void startSum(String user)
25   {
26     if (state.containsKey(user))
27       throw new IllegalStateException("Sumation for " + user + " already in progress, state: " + state.get(user));
28
29     state.put(user, 0l);
30   }
31
32   public synchronized Optional<Long> getSum(String user)
33   {
34     return Optional.ofNullable(state.get(user));
35   }
36
37   public synchronized void addToSum(String user, Integer value)
38   {
39     if (!state.containsKey(user))
40       throw new IllegalStateException("No sumation for " + user + " in progress");
41     if (value == null || value < 1)
42       throw new IllegalArgumentException("Not a positive number: " + value);
43
44     long result = state.get(user) + value;
45     state.put(user, result);
46   }
47
48   public synchronized Long endSum(String user)
49   {
50     if (!state.containsKey(user))
51       throw new IllegalStateException("No sumation for " + user + " in progress");
52
53     return state.remove(user);
54   }
55
56   protected Map<String, Long> getState()
57   {
58     return state;
59   }
60 }