f6cddca8c4d206f8b6ba06d9b4753b8d9e7c5d6c
[demos/testing] / src / main / java / de / juplo / demo / RestController.java
1 package de.juplo.demo;
2
3
4 import org.springframework.http.MediaType;
5 import org.springframework.web.bind.annotation.GetMapping;
6 import org.springframework.web.bind.annotation.RequestParam;
7 import org.springframework.web.reactive.function.client.WebClientResponseException;
8 import org.springframework.web.reactive.function.client.WebClientResponseException.NotFound;
9 import reactor.core.publisher.Mono;
10
11
12 /**
13  * Fetches and returns data from a remote-webserver.
14  * @author Kai Moritz
15  */
16 @org.springframework.web.bind.annotation.RestController
17 public class RestController
18 {
19   RemoteContentService service;
20
21
22   public RestController(RemoteContentService service)
23   {
24     this.service = service;
25   }
26
27
28   @GetMapping(path = { "", "/" }, produces = MediaType.TEXT_PLAIN_VALUE)
29   public Mono<String> fetch(@RequestParam String path)
30   {
31     return
32         service
33             .getRemoteText(path)
34             .onErrorResume(t ->
35             {
36               if(t.getClass().equals(NotFound.class))
37                 return Mono.error(t);
38               if(!(t instanceof WebClientResponseException))
39                 return
40                     Mono.error(
41                         WebClientResponseException.create(
42                             500,
43                             "Internal Server Error - Cause: " + t.getMessage(),
44                             null,
45                             null,
46                             null));
47
48               return
49                   Mono.error(
50                       WebClientResponseException.create(
51                           503,
52                           "Service Unavailable - Cause: " + t.getMessage(),
53                           null,
54                           null,
55                           null));
56             });
57   }
58 }