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