test: HandoverIT-POC - Each `TestWriter` writes only to one chat-room
[demos/kafka/chat] / src / test / java / de / juplo / kafka / chat / backend / TestWriter.java
1 package de.juplo.kafka.chat.backend;
2
3 import de.juplo.kafka.chat.backend.api.ChatRoomInfoTo;
4 import de.juplo.kafka.chat.backend.api.MessageTo;
5 import lombok.extern.slf4j.Slf4j;
6 import org.springframework.http.HttpStatus;
7 import org.springframework.http.MediaType;
8 import org.springframework.web.reactive.function.client.WebClient;
9 import org.springframework.web.reactive.function.client.WebClientResponseException;
10 import reactor.core.publisher.Mono;
11 import reactor.util.retry.Retry;
12
13 import java.nio.charset.Charset;
14 import java.time.Duration;
15 import java.util.concurrent.ThreadLocalRandom;
16
17
18 @Slf4j
19 public class TestWriter implements Runnable
20 {
21   @Override
22   public void run()
23   {
24     for (int i = 0; running; i++)
25     {
26       String message = "Message #" + i;
27       try
28       {
29         sendMessage(chatRoom, message)
30             .retryWhen(Retry.fixedDelay(10, Duration.ofSeconds(1)))
31             .map(MessageTo::toString)
32             .onErrorResume(throwable ->
33             {
34               WebClientResponseException e = (WebClientResponseException)throwable.getCause();
35               return Mono.just(e.getResponseBodyAsString(Charset.defaultCharset()));
36             })
37             .subscribe(result -> log.info(
38                 "{} sent a message to {}: {}",
39                 user,
40                 chatRoom,
41                 result));
42
43         Thread.sleep(ThreadLocalRandom.current().nextLong(700, 1000));
44       }
45       catch (Exception e)
46       {
47         throw new RuntimeException(e);
48       }
49     }
50   }
51
52   private Mono<MessageTo> sendMessage(
53       ChatRoomInfoTo chatRoom,
54       String message)
55   {
56     return webClient
57         .put()
58         .uri(
59             "/{chatRoomId}/{username}/{serial}",
60             chatRoom.getId(),
61             user.getName(),
62             user.nextSerial())
63         .contentType(MediaType.TEXT_PLAIN)
64         .accept(MediaType.APPLICATION_JSON)
65         .bodyValue(message)
66         .exchangeToMono(response ->
67         {
68           if (response.statusCode().equals(HttpStatus.OK))
69           {
70             return response.bodyToMono(MessageTo.class);
71           }
72           else
73           {
74             return response.createError();
75           }
76         });
77   }
78
79
80   private final WebClient webClient;
81   private final ChatRoomInfoTo chatRoom;
82   private final User user;
83
84   volatile boolean running = true;
85
86
87   TestWriter(Integer port, ChatRoomInfoTo chatRoom, String username)
88   {
89     webClient = WebClient.create("http://localhost:" + port);
90     this.chatRoom = chatRoom;
91     user = new User(username);
92   }
93 }