import org.apache.kafka.clients.consumer.ConsumerRecord;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
-import java.util.regex.Pattern;
-
@Slf4j
public class SumRecordHandler implements RecordHandler<String, String>
{
- final static Pattern PATTERN = Pattern.compile("\\W+");
-
-
- private final Map<Integer, Map<String, Map<String, Long>>> seen = new HashMap<>();
+ private final Map<Integer, Map<String, List<Long>>> seen = new HashMap<>();
+ private final Map<Integer, SumBusinessLogic> state = new HashMap<>();
@Override
{
Integer partition = record.partition();
String user = record.key();
- Map<String, Map<String, Long>> users = seen.get(partition);
-
- Map<String, Long> words = users.get(user);
- if (words == null)
- {
- words = new HashMap<>();
- users.put(user, words);
- }
-
- for (String word : PATTERN.split(record.value()))
+ String message = record.value();
+ switch (message)
{
- Long num = words.get(word);
- if (num == null)
- {
- num = 1l;
- }
- else
- {
- num++;
- }
- words.put(word, num);
+ case "START":
+ state.get(partition).startSum(user);
+ return;
+
+ case "END":
+ Long result = state.get(partition).endSum(user);
+ log.info("New result for {}: {}", user, result);
+ return;
+
+ default:
+ state.get(partition).addToSum(user, Integer.parseInt(message));
+ return;
}
}
- public void addPartition(Integer partition, Map<String, Map<String, Long>> statistics)
+ protected void addPartition(Integer partition, StateDocument document)
{
- seen.put(partition, statistics);
+ this.seen.put(partition, document.seen);
+ this.state.put(partition, new SumBusinessLogic(document.state));
}
- public Map<String, Map<String, Long>> removePartition(Integer partition)
+ protected StateDocument removePartition(Integer partition)
{
- return seen.remove(partition);
+ return new StateDocument(
+ partition,
+ this.state.remove(partition).getState(),
+ this.seen.remove(partition));
}
- public Map<Integer, Map<String, Map<String, Long>>> getSeen()
+ public Map<Integer, Map<String, List<Long>>> getSeen()
{
return seen;
}