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