test: HandoverIT-POC - Added a delay to the sending-loop
[demos/kafka/chat] / src / test / java / de / juplo / kafka / chat / backend / TestClient.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 reactor.core.publisher.Mono;
10 import reactor.util.retry.Retry;
11
12 import java.time.Duration;
13 import java.util.concurrent.ThreadLocalRandom;
14
15
16 @Slf4j
17 public class TestClient
18 {
19   public void run()
20   {
21     for (int i = 0; i < 100; i++)
22     {
23       String message = "Message #" + i;
24       for (ChatRoomInfoTo chatRoom : chatRooms)
25       {
26         sendMessage(chatRoom, message)
27             .retryWhen(Retry.fixedDelay(10, Duration.ofSeconds(1)))
28             .map(MessageTo::toString)
29             .subscribe(result -> log.info(
30                 "{} sent message \"{}\" to {}",
31                 user,
32                 message,
33                 chatRoom));
34       }
35       try
36       {
37         Thread.sleep(ThreadLocalRandom.current().nextLong(700, 1000));
38       }
39       catch (Exception e)
40       {
41         throw new RuntimeException(e);
42       }
43     }
44   }
45
46   private Mono<MessageTo> sendMessage(
47       ChatRoomInfoTo chatRoom,
48       String message)
49   {
50     return webClient
51         .put()
52         .uri(
53             "/{chatRoomId}/{username}/{serial}",
54             chatRoom.getId(),
55             user.getName(),
56             user.nextSerial())
57         .contentType(MediaType.TEXT_PLAIN)
58         .accept(MediaType.APPLICATION_JSON)
59         .bodyValue(message)
60         .exchangeToMono(response ->
61         {
62           if (response.statusCode().equals(HttpStatus.OK))
63           {
64             return response.bodyToMono(MessageTo.class);
65           }
66           else
67           {
68             return response.createError();
69           }
70         });
71   }
72
73
74   private final WebClient webClient;
75   private final ChatRoomInfoTo[] chatRooms;
76   private final User user;
77
78
79   TestClient(Integer port, ChatRoomInfoTo[] chatRooms, String username)
80   {
81     webClient = WebClient.create("http://localhost:" + port);
82     this.chatRooms = chatRooms;
83     user = new User(username);
84   }
85 }