Merge "Make assertions of log messages better"
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / dmaap / DmaapMessageHandler.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2020 Nordix Foundation
6  * %%
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21 package org.oransc.policyagent.dmaap;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.JsonObject;
26
27 import java.io.IOException;
28 import java.util.Optional;
29
30 import org.onap.dmaap.mr.client.MRBatchingPublisher;
31 import org.oransc.policyagent.clients.AsyncRestClient;
32 import org.oransc.policyagent.dmaap.DmaapRequestMessage.Operation;
33 import org.oransc.policyagent.exceptions.ServiceException;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.springframework.http.HttpStatus;
37 import org.springframework.http.ResponseEntity;
38 import org.springframework.web.reactive.function.client.WebClientResponseException;
39 import reactor.core.publisher.Mono;
40
41 /**
42  * The class handles incoming requests from DMAAP.
43  * <p>
44  * That means: invoke a REST call towards this services and to send back a
45  * response though DMAAP
46  */
47 public class DmaapMessageHandler {
48     private static final Logger logger = LoggerFactory.getLogger(DmaapMessageHandler.class);
49     private static Gson gson = new GsonBuilder() //
50         .create(); //
51     private final MRBatchingPublisher dmaapClient;
52     private final AsyncRestClient agentClient;
53
54     public DmaapMessageHandler(MRBatchingPublisher dmaapClient, AsyncRestClient agentClient) {
55         this.agentClient = agentClient;
56         this.dmaapClient = dmaapClient;
57     }
58
59     public void handleDmaapMsg(String msg) {
60         try {
61             String result = this.createTask(msg).block();
62             logger.debug("handleDmaapMsg: {}", result);
63         } catch (Exception throwable) {
64             logger.warn("handleDmaapMsg failure {}", throwable.getMessage());
65         }
66     }
67
68     Mono<String> createTask(String msg) {
69         try {
70             DmaapRequestMessage dmaapRequestMessage = gson.fromJson(msg, ImmutableDmaapRequestMessage.class);
71             return this.invokePolicyAgent(dmaapRequestMessage) //
72                 .onErrorResume(t -> handleAgentCallError(t, msg, dmaapRequestMessage)) //
73                 .flatMap(
74                     response -> sendDmaapResponse(response.getBody(), dmaapRequestMessage, response.getStatusCode()));
75         } catch (Exception e) {
76             String errorMsg = "Received unparsable message from DMAAP: \"" + msg + "\", reason: " + e.getMessage();
77             return Mono.error(new ServiceException(errorMsg)); // Cannot make any response
78         }
79     }
80
81     private Mono<ResponseEntity<String>> handleAgentCallError(Throwable t, String originalMessage,
82         DmaapRequestMessage dmaapRequestMessage) {
83         logger.debug("Agent call failed: {}", t.getMessage());
84         HttpStatus status = HttpStatus.NOT_FOUND;
85         String errorMessage = t.getMessage();
86         if (t instanceof WebClientResponseException) {
87             WebClientResponseException exception = (WebClientResponseException) t;
88             status = exception.getStatusCode();
89             errorMessage = exception.getResponseBodyAsString();
90         } else if (t instanceof ServiceException) {
91             status = HttpStatus.BAD_REQUEST;
92             errorMessage = prepareBadOperationErrorMessage(t, originalMessage);
93
94         }
95         return sendDmaapResponse(errorMessage, dmaapRequestMessage, status) //
96             .flatMap(notUsed -> Mono.empty());
97     }
98
99     private String prepareBadOperationErrorMessage(Throwable t, String originalMessage) {
100         String operationParameterStart = "operation\":\"";
101         int indexOfOperationStart = originalMessage.indexOf(operationParameterStart) + operationParameterStart.length();
102         int indexOfOperationEnd = originalMessage.indexOf("\",\"", indexOfOperationStart);
103         String badOperation = originalMessage.substring(indexOfOperationStart, indexOfOperationEnd);
104         return t.getMessage().replace("null", badOperation);
105     }
106
107     private Mono<ResponseEntity<String>> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
108         DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
109         String uri = dmaapRequestMessage.url();
110
111         if (operation == Operation.DELETE) {
112             return agentClient.deleteForEntity(uri);
113         } else if (operation == Operation.GET) {
114             return agentClient.getForEntity(uri);
115         } else if (operation == Operation.PUT) {
116             return agentClient.putForEntity(uri, payload(dmaapRequestMessage));
117         } else if (operation == Operation.POST) {
118             return agentClient.postForEntity(uri, payload(dmaapRequestMessage));
119         } else {
120             return Mono.error(new ServiceException("Not implemented operation: " + operation));
121         }
122
123     }
124
125     private String payload(DmaapRequestMessage message) {
126         Optional<JsonObject> payload = message.payload();
127         if (payload.isPresent()) {
128             return gson.toJson(payload.get());
129         } else {
130             logger.warn("Expected payload in message from DMAAP: {}", message);
131             return "";
132         }
133     }
134
135     private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
136         HttpStatus status) {
137         return createDmaapResponseMessage(dmaapRequestMessage, response, status) //
138             .flatMap(this::sendToDmaap) //
139             .onErrorResume(this::handleResponseCallError);
140     }
141
142     private Mono<String> sendToDmaap(String body) {
143         try {
144             logger.debug("sendToDmaap: {} ", body);
145             dmaapClient.send(body);
146             dmaapClient.sendBatchWithResponse();
147             return Mono.just("OK");
148         } catch (IOException e) {
149             return Mono.error(e);
150         }
151     }
152
153     private Mono<String> handleResponseCallError(Throwable t) {
154         logger.debug("Failed to send response to DMaaP: {}", t.getMessage());
155         return Mono.empty();
156     }
157
158     private Mono<String> createDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
159         HttpStatus status) {
160         DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
161             .status(status.toString()) //
162             .message(response == null ? "" : response) //
163             .type("response") //
164             .correlationId(dmaapRequestMessage.correlationId() == null ? "" : dmaapRequestMessage.correlationId()) //
165             .originatorId(dmaapRequestMessage.originatorId() == null ? "" : dmaapRequestMessage.originatorId()) //
166             .requestId(dmaapRequestMessage.requestId() == null ? "" : dmaapRequestMessage.requestId()) //
167             .timestamp(dmaapRequestMessage.timestamp() == null ? "" : dmaapRequestMessage.timestamp()) //
168             .build();
169         String str = gson.toJson(dmaapResponseMessage);
170         return Mono.just(str);
171
172     }
173 }