GRÜN: Neue Erwartungen umgesetzt
[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 Optional<Long> getSum(String user)
26   {
27     return Optional.ofNullable(state.get(user));
28   }
29
30   public synchronized void addToSum(String user, Integer value)
31   {
32     if (value == null || value < 1)
33       throw new IllegalArgumentException("Not a positive number: " + value);
34
35     long sum =
36         Optional
37             .ofNullable(state.get(user))
38             .orElse(0l);
39     state.put(user, sum + value);
40   }
41
42   public synchronized Long calculate(String user)
43   {
44     if (!state.containsKey(user))
45       throw new IllegalStateException("No sumation for " + user + " in progress");
46
47     return state.remove(user);
48   }
49
50   protected Map<String, Long> getState()
51   {
52     return state;
53   }
54 }