Die App führt die Berechnung aus
[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, AdderResult> state;
12
13
14   public AdderBusinessLogic()
15   {
16     this(new HashMap<>());
17   }
18
19   public AdderBusinessLogic(Map<String, AdderResult> 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)).map(result -> result.sum);
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             .map(result -> result.sum)
39             .orElse(0l);
40     state.put(user, new AdderResult(value, sum + value));
41   }
42
43   public synchronized AdderResult calculate(String user)
44   {
45     if (!state.containsKey(user))
46       throw new IllegalStateException("No sumation for " + user + " in progress");
47
48     return state.remove(user);
49   }
50 }