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