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