Merge "Add description to parameters in the remaining controllers"
[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.WebClientException;
39 import org.springframework.web.reactive.function.client.WebClientResponseException;
40 import reactor.core.publisher.Mono;
41
42 /**
43  * The class handles incoming requests from DMAAP.
44  * <p>
45  * That means: invoke a REST call towards this services and to send back a
46  * response though DMAAP
47  */
48 public class DmaapMessageHandler {
49     private static final Logger logger = LoggerFactory.getLogger(DmaapMessageHandler.class);
50     private static Gson gson = new GsonBuilder() //
51         .create(); //
52     private final MRBatchingPublisher dmaapClient;
53     private final AsyncRestClient agentClient;
54
55     public DmaapMessageHandler(MRBatchingPublisher dmaapClient, AsyncRestClient agentClient) {
56         this.agentClient = agentClient;
57         this.dmaapClient = dmaapClient;
58     }
59
60     public void handleDmaapMsg(String msg) {
61         try {
62             String result = this.createTask(msg).block();
63             logger.debug("handleDmaapMsg: {}", result);
64         } catch (Exception throwable) {
65             logger.warn("handleDmaapMsg failure {}", throwable.getMessage());
66         }
67     }
68
69     Mono<String> createTask(String msg) {
70         try {
71             DmaapRequestMessage dmaapRequestMessage = gson.fromJson(msg, ImmutableDmaapRequestMessage.class);
72             return this.invokePolicyAgent(dmaapRequestMessage) //
73                 .onErrorResume(t -> handleAgentCallError(t, msg, dmaapRequestMessage)) //
74                 .flatMap(
75                     response -> sendDmaapResponse(response.getBody(), dmaapRequestMessage, response.getStatusCode()));
76         } catch (Exception e) {
77             String errorMsg = "Received unparsable message from DMAAP: \"" + msg + "\", reason: " + e.getMessage();
78             return Mono.error(new ServiceException(errorMsg)); // Cannot make any response
79         }
80     }
81
82     private Mono<ResponseEntity<String>> handleAgentCallError(Throwable t, String originalMessage,
83         DmaapRequestMessage dmaapRequestMessage) {
84         logger.debug("Agent call failed: {}", t.getMessage());
85         HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
86         String errorMessage = t.getMessage();
87         if (t instanceof WebClientResponseException) {
88             WebClientResponseException exception = (WebClientResponseException) t;
89             status = exception.getStatusCode();
90             errorMessage = exception.getResponseBodyAsString();
91         } else if (t instanceof ServiceException) {
92             status = HttpStatus.BAD_REQUEST;
93             errorMessage = prepareBadOperationErrorMessage(t, originalMessage);
94         } else if (!(t instanceof WebClientException)) {
95             logger.warn("Unexpected exception ", t);
96         }
97         return sendDmaapResponse(errorMessage, dmaapRequestMessage, status) //
98             .flatMap(notUsed -> Mono.empty());
99     }
100
101     private String prepareBadOperationErrorMessage(Throwable t, String originalMessage) {
102         String operationParameterStart = "operation\":\"";
103         int indexOfOperationStart = originalMessage.indexOf(operationParameterStart) + operationParameterStart.length();
104         int indexOfOperationEnd = originalMessage.indexOf("\",\"", indexOfOperationStart);
105         String badOperation = originalMessage.substring(indexOfOperationStart, indexOfOperationEnd);
106         return t.getMessage().replace("null", badOperation);
107     }
108
109     private Mono<ResponseEntity<String>> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
110         DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
111         String uri = dmaapRequestMessage.url();
112
113         if (operation == Operation.DELETE) {
114             return agentClient.deleteForEntity(uri);
115         } else if (operation == Operation.GET) {
116             return agentClient.getForEntity(uri);
117         } else if (operation == Operation.PUT) {
118             return agentClient.putForEntity(uri, payload(dmaapRequestMessage));
119         } else if (operation == Operation.POST) {
120             return agentClient.postForEntity(uri, payload(dmaapRequestMessage));
121         } else {
122             return Mono.error(new ServiceException("Not implemented operation: " + operation));
123         }
124     }
125
126     private String payload(DmaapRequestMessage message) {
127         Optional<JsonObject> payload = message.payload();
128         if (payload.isPresent()) {
129             return gson.toJson(payload.get());
130         } else {
131             logger.warn("Expected payload in message from DMAAP: {}", message);
132             return "";
133         }
134     }
135
136     private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
137         HttpStatus status) {
138         return createDmaapResponseMessage(dmaapRequestMessage, response, status) //
139             .flatMap(this::sendToDmaap) //
140             .onErrorResume(this::handleResponseCallError);
141     }
142
143     private Mono<String> sendToDmaap(String body) {
144         try {
145             logger.debug("sendToDmaap: {} ", body);
146             dmaapClient.send(body);
147             dmaapClient.sendBatchWithResponse();
148             return Mono.just("OK");
149         } catch (IOException e) {
150             return Mono.error(e);
151         }
152     }
153
154     private Mono<String> handleResponseCallError(Throwable t) {
155         logger.debug("Failed to send response to DMaaP: {}", t.getMessage());
156         return Mono.empty();
157     }
158
159     private Mono<String> createDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
160         HttpStatus status) {
161         DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
162             .status(status.toString()) //
163             .message(response == null ? "" : response) //
164             .type("response") //
165             .correlationId(dmaapRequestMessage.correlationId() == null ? "" : dmaapRequestMessage.correlationId()) //
166             .originatorId(dmaapRequestMessage.originatorId() == null ? "" : dmaapRequestMessage.originatorId()) //
167             .requestId(dmaapRequestMessage.requestId() == null ? "" : dmaapRequestMessage.requestId()) //
168             .timestamp(dmaapRequestMessage.timestamp() == null ? "" : dmaapRequestMessage.timestamp()) //
169             .build();
170         String str = gson.toJson(dmaapResponseMessage);
171         return Mono.just(str);
172
173     }
174 }