counter: 1.1.3 - Implemented an integration test for the old message-format
[demos/kafka/wordcount] / src / main / java / de / juplo / kafka / wordcount / counter / CounterStreamProcessor.java
1 package de.juplo.kafka.wordcount.counter;
2
3 import com.fasterxml.jackson.core.JsonProcessingException;
4 import com.fasterxml.jackson.databind.ObjectMapper;
5 import lombok.extern.slf4j.Slf4j;
6 import org.apache.kafka.streams.KafkaStreams;
7 import org.apache.kafka.streams.KeyValue;
8 import org.apache.kafka.streams.StreamsBuilder;
9 import org.apache.kafka.streams.kstream.KStream;
10
11 import java.util.Properties;
12
13
14 @Slf4j
15 public class CounterStreamProcessor
16 {
17         public final KafkaStreams streams;
18
19
20         public CounterStreamProcessor(
21                         String inputTopic,
22                         String outputTopic,
23                         Properties properties,
24                         ObjectMapper mapper)
25         {
26                 StreamsBuilder builder = new StreamsBuilder();
27
28                 KStream<String, String> source = builder.stream(inputTopic);
29                 source
30                                 .map((username, word) ->
31                                 {
32                                         try
33                                         {
34                                                 String key = mapper.writeValueAsString(Key.of(username, word));
35                                                 return new KeyValue<>(key, word);
36                                         }
37                                         catch (JsonProcessingException e)
38                                         {
39                                                 throw new RuntimeException(e);
40                                         }
41                                 })
42                                 .groupByKey()
43                                 .count()
44                                 .mapValues(value->Long.toString(value))
45                                 .toStream()
46                                 .to(outputTopic);
47
48                 streams = new KafkaStreams(builder.build(), properties);
49         }
50
51         public void start()
52         {
53                 log.info("Starting Stream-Processor");
54                 streams.start();
55         }
56
57         public void stop()
58         {
59                 log.info("Stopping Stream-Processor");
60                 streams.close();
61         }
62 }