Merge "Renamed things to fit with namechange of RicSynchronizationTask"
[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         this.createTask(msg) //
60             .subscribe(message -> logger.debug("handleDmaapMsg: {}", message), //
61                 throwable -> logger.warn("handleDmaapMsg failure ", throwable), //
62                 () -> logger.debug("handleDmaapMsg complete"));
63     }
64
65     Mono<String> createTask(String msg) {
66         try {
67             DmaapRequestMessage dmaapRequestMessage = gson.fromJson(msg, ImmutableDmaapRequestMessage.class);
68             return this.invokePolicyAgent(dmaapRequestMessage) //
69                 .onErrorResume(t -> handleAgentCallError(t, msg, dmaapRequestMessage)) //
70                 .flatMap(
71                     response -> sendDmaapResponse(response.getBody(), dmaapRequestMessage, response.getStatusCode()));
72         } catch (Exception e) {
73             logger.warn("Received unparsable message from DMAAP: {}", msg);
74             return Mono.error(e); // Cannot make any response
75         }
76     }
77
78     private Mono<ResponseEntity<String>> handleAgentCallError(Throwable t, String originalMessage,
79         DmaapRequestMessage dmaapRequestMessage) {
80         logger.debug("Agent call failed: {}", t.getMessage());
81         HttpStatus status = HttpStatus.NOT_FOUND;
82         String errorMessage = t.getMessage();
83         if (t instanceof WebClientResponseException) {
84             WebClientResponseException exception = (WebClientResponseException) t;
85             status = exception.getStatusCode();
86             errorMessage = exception.getResponseBodyAsString();
87         } else if (t instanceof ServiceException) {
88             status = HttpStatus.BAD_REQUEST;
89             errorMessage = prepareBadOperationErrorMessage(t, originalMessage);
90
91         }
92         return sendDmaapResponse(errorMessage, dmaapRequestMessage, status) //
93             .flatMap(notUsed -> Mono.empty());
94     }
95
96     private String prepareBadOperationErrorMessage(Throwable t, String originalMessage) {
97         String operationParameterStart = "operation\":\"";
98         int indexOfOperationStart = originalMessage.indexOf(operationParameterStart) + operationParameterStart.length();
99         int indexOfOperationEnd = originalMessage.indexOf("\",\"", indexOfOperationStart);
100         String badOperation = originalMessage.substring(indexOfOperationStart, indexOfOperationEnd);
101         return t.getMessage().replace("null", badOperation);
102     }
103
104     private Mono<ResponseEntity<String>> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
105         DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
106         String uri = dmaapRequestMessage.url();
107
108         if (operation == Operation.DELETE) {
109             return agentClient.deleteForEntity(uri);
110         } else if (operation == Operation.GET) {
111             return agentClient.getForEntity(uri);
112         } else if (operation == Operation.PUT) {
113             return agentClient.putForEntity(uri, payload(dmaapRequestMessage));
114         } else if (operation == Operation.POST) {
115             return agentClient.postForEntity(uri, payload(dmaapRequestMessage));
116         } else {
117             return Mono.error(new ServiceException("Not implemented operation: " + operation));
118         }
119
120     }
121
122     private String payload(DmaapRequestMessage message) {
123         Optional<JsonObject> payload = message.payload();
124         if (payload.isPresent()) {
125             return gson.toJson(payload.get());
126         } else {
127             logger.warn("Expected payload in message from DMAAP: {}", message);
128             return "";
129         }
130     }
131
132     private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
133         HttpStatus status) {
134         return createDmaapResponseMessage(dmaapRequestMessage, response, status) //
135             .flatMap(this::sendToDmaap) //
136             .onErrorResume(this::handleResponseCallError);
137     }
138
139     private Mono<String> sendToDmaap(String body) {
140         try {
141             logger.debug("sendToDmaap: {} ", body);
142             dmaapClient.send(body);
143             dmaapClient.sendBatchWithResponse();
144             return Mono.just("OK");
145         } catch (IOException e) {
146             return Mono.error(e);
147         }
148     }
149
150     private Mono<String> handleResponseCallError(Throwable t) {
151         logger.debug("Failed to send response to DMaaP: {}", t.getMessage());
152         return Mono.empty();
153     }
154
155     private Mono<String> createDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
156         HttpStatus status) {
157         DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
158             .status(status.toString()) //
159             .message(response == null ? "" : response) //
160             .type("response") //
161             .correlationId(dmaapRequestMessage.correlationId() == null ? "" : dmaapRequestMessage.correlationId()) //
162             .originatorId(dmaapRequestMessage.originatorId() == null ? "" : dmaapRequestMessage.originatorId()) //
163             .requestId(dmaapRequestMessage.requestId() == null ? "" : dmaapRequestMessage.requestId()) //
164             .timestamp(dmaapRequestMessage.timestamp() == null ? "" : dmaapRequestMessage.timestamp()) //
165             .build();
166         String str = gson.toJson(dmaapResponseMessage);
167         return Mono.just(str);
168
169     }
170 }