refactor: Refined packaging (renamed packages and classes)
[demos/kafka/chat] / src / main / java / de / juplo / kafka / chat / backend / api / ChatBackendControllerAdvice.java
1 package de.juplo.kafka.chat.backend.api;
2
3 import de.juplo.kafka.chat.backend.domain.MessageMutationException;
4 import org.springframework.beans.factory.annotation.Value;
5 import org.springframework.http.HttpStatus;
6 import org.springframework.http.ProblemDetail;
7 import org.springframework.web.bind.annotation.ControllerAdvice;
8 import org.springframework.web.bind.annotation.ExceptionHandler;
9 import org.springframework.web.server.ServerWebExchange;
10 import org.springframework.web.util.UriComponentsBuilder;
11
12 import java.util.Date;
13
14
15 @ControllerAdvice
16 public class ChatBackendControllerAdvice
17 {
18   @Value("${server.context-path:/}")
19   String contextPath;
20
21   @ExceptionHandler(MessageMutationException.class)
22   public final ProblemDetail handleException(
23       MessageMutationException e,
24       ServerWebExchange exchange,
25       UriComponentsBuilder uriComponentsBuilder)
26   {
27     final HttpStatus status = HttpStatus.BAD_REQUEST;
28     ProblemDetail problem = ProblemDetail.forStatus(status);
29
30     problem.setProperty("timestamp", new Date());
31
32     problem.setProperty("requestId", exchange.getRequest().getId());
33
34     problem.setType(uriComponentsBuilder.replacePath(contextPath).path("/problem/message-mutation").build().toUri());
35     StringBuilder stringBuilder = new StringBuilder();
36     stringBuilder.append(status.getReasonPhrase());
37     stringBuilder.append(" - ");
38     stringBuilder.append(e.getMessage());
39     problem.setTitle(stringBuilder.toString());
40
41     stringBuilder.setLength(0);
42     stringBuilder.append("The existing message with user=");
43     stringBuilder.append(e.getExisting().getUser());
44     stringBuilder.append(" and id=");
45     stringBuilder.append(e.getExisting().getId());
46     stringBuilder.append(" cannot be mutated!");
47     problem.setDetail(stringBuilder.toString());
48
49     problem.setProperty("mutatedMessage", e.getMutated());
50
51     problem.setProperty("existingMessage", e.getExisting());
52
53     return problem;
54   }
55 }