1 package de.juplo.kafka.wordcount.recorder;
3 import org.apache.kafka.clients.producer.KafkaProducer;
4 import org.apache.kafka.clients.producer.ProducerRecord;
5 import org.springframework.http.HttpStatus;
6 import org.springframework.http.ResponseEntity;
7 import org.springframework.util.MimeTypeUtils;
8 import org.springframework.web.bind.annotation.PathVariable;
9 import org.springframework.web.bind.annotation.PostMapping;
10 import org.springframework.web.bind.annotation.RequestBody;
11 import org.springframework.web.bind.annotation.RestController;
12 import org.springframework.web.context.request.async.DeferredResult;
14 import javax.validation.constraints.NotEmpty;
18 public class RecorderController
20 private final String topic;
21 private final KafkaProducer<String, String> producer;
24 public RecorderController(RecorderApplicationProperties properties, KafkaProducer<String,String> producer)
26 this.topic = properties.getTopic();
27 this.producer = producer;
33 MimeTypeUtils.TEXT_PLAIN_VALUE,
34 MimeTypeUtils.APPLICATION_JSON_VALUE
36 produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
37 DeferredResult<ResponseEntity<RecordingResult>> speak(
39 @NotEmpty(message = "A username must be provided")
42 @NotEmpty(message = "The spoken sentence must not be empty!")
45 DeferredResult<ResponseEntity<RecordingResult>> result = new DeferredResult<>();
47 ProducerRecord<String, String> record = new ProducerRecord<>(topic, username, sentence);
48 producer.send(record, (metadata, exception) ->
53 ResponseEntity.ok(RecordingResult.of(
64 result.setErrorResult(
66 .internalServerError()
67 .body(RecordingResult.of(
73 HttpStatus.INTERNAL_SERVER_ERROR.value(),
74 exception.toString())));