ecd9590de696b14501145682be4dbd58a0b6c955
[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 (!state.containsKey(user))
33       throw new IllegalStateException("No sumation for " + user + " in progress");
34     if (value == null || value < 1)
35       throw new IllegalArgumentException("Not a positive number: " + value);
36
37     long result = state.get(user) + value;
38     state.put(user, result);
39   }
40
41   public synchronized Long calculate(String user)
42   {
43     if (!state.containsKey(user))
44       throw new IllegalStateException("No sumation for " + user + " in progress");
45
46     return state.remove(user);
47   }
48
49   protected Map<String, Long> getState()
50   {
51     return state;
52   }
53 }