226b54e9a2093612bd38491bfe3be3b6ff97cb49
[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.util.Optional;
28
29 import org.oransc.policyagent.clients.AsyncRestClient;
30 import org.oransc.policyagent.dmaap.DmaapRequestMessage.Operation;
31 import org.oransc.policyagent.exceptions.ServiceException;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.springframework.http.HttpStatus;
35 import org.springframework.http.ResponseEntity;
36 import org.springframework.web.reactive.function.client.WebClientException;
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 response though DMAAP
44  */
45 public class DmaapMessageHandler {
46     private static final Logger logger = LoggerFactory.getLogger(DmaapMessageHandler.class);
47     private static Gson gson = new GsonBuilder() //
48         .create(); //
49     private final AsyncRestClient dmaapClient;
50     private final AsyncRestClient agentClient;
51
52     public DmaapMessageHandler(AsyncRestClient dmaapClient, AsyncRestClient agentClient) {
53         this.agentClient = agentClient;
54         this.dmaapClient = dmaapClient;
55     }
56
57     public void handleDmaapMsg(String msg) {
58         try {
59             String result = this.createTask(msg).block();
60             logger.debug("handleDmaapMsg: {}", result);
61         } catch (Exception throwable) {
62             logger.warn("handleDmaapMsg failure {}", throwable.getMessage());
63         }
64     }
65
66     Mono<String> createTask(String msg) {
67         try {
68             DmaapRequestMessage dmaapRequestMessage = gson.fromJson(msg, ImmutableDmaapRequestMessage.class);
69             return this.invokePolicyAgent(dmaapRequestMessage) //
70                 .onErrorResume(t -> handleAgentCallError(t, dmaapRequestMessage)) //
71                 .flatMap(
72                     response -> sendDmaapResponse(response.getBody(), dmaapRequestMessage, response.getStatusCode()));
73         } catch (Exception e) {
74             String errorMsg = "Received unparsable message from DMAAP: \"" + msg + "\", reason: " + e.getMessage();
75             return Mono.error(new ServiceException(errorMsg)); // Cannot make any response
76         }
77     }
78
79     private Mono<ResponseEntity<String>> handleAgentCallError(Throwable error,
80         DmaapRequestMessage dmaapRequestMessage) {
81         logger.debug("Agent call failed: {}", error.getMessage());
82         HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
83         String errorMessage = error.getMessage();
84         if (error instanceof WebClientResponseException) {
85             WebClientResponseException exception = (WebClientResponseException) error;
86             status = exception.getStatusCode();
87             errorMessage = exception.getResponseBodyAsString();
88         } else if (error instanceof ServiceException) {
89             status = HttpStatus.BAD_REQUEST;
90             errorMessage = error.getMessage();
91         } else if (!(error instanceof WebClientException)) {
92             logger.warn("Unexpected exception ", error);
93         }
94         return sendDmaapResponse(errorMessage, dmaapRequestMessage, status) //
95             .flatMap(notUsed -> Mono.empty());
96     }
97
98     private Mono<ResponseEntity<String>> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
99         DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
100         String uri = dmaapRequestMessage.url();
101
102         if (operation == Operation.DELETE) {
103             return agentClient.deleteForEntity(uri);
104         } else if (operation == Operation.GET) {
105             return agentClient.getForEntity(uri);
106         } else if (operation == Operation.PUT) {
107             return agentClient.putForEntity(uri, payload(dmaapRequestMessage));
108         } else if (operation == Operation.POST) {
109             return agentClient.postForEntity(uri, payload(dmaapRequestMessage));
110         } else {
111             return Mono.error(new ServiceException("Not implemented operation: " + operation));
112         }
113     }
114
115     private String payload(DmaapRequestMessage message) {
116         Optional<JsonObject> payload = message.payload();
117         if (payload.isPresent()) {
118             return gson.toJson(payload.get());
119         } else {
120             logger.warn("Expected payload in message from DMAAP: {}", message);
121             return "";
122         }
123     }
124
125     private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
126         HttpStatus status) {
127         return createDmaapResponseMessage(dmaapRequestMessage, response, status) //
128             .flatMap(this::sendToDmaap) //
129             .onErrorResume(this::handleResponseCallError);
130     }
131
132     private Mono<String> sendToDmaap(String body) {
133         logger.debug("sendToDmaap: {} ", body);
134         return dmaapClient.post("", "[" + body + "]");
135     }
136
137     private Mono<String> handleResponseCallError(Throwable t) {
138         logger.debug("Failed to send response to DMaaP: {}", t.getMessage());
139         return Mono.empty();
140     }
141
142     private Mono<String> createDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
143         HttpStatus status) {
144         DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
145             .status(status.toString()) //
146             .message(response == null ? "" : response) //
147             .type("response") //
148             .correlationId(dmaapRequestMessage.correlationId() == null ? "" : dmaapRequestMessage.correlationId()) //
149             .originatorId(dmaapRequestMessage.originatorId() == null ? "" : dmaapRequestMessage.originatorId()) //
150             .requestId(dmaapRequestMessage.requestId() == null ? "" : dmaapRequestMessage.requestId()) //
151             .timestamp(dmaapRequestMessage.timestamp() == null ? "" : dmaapRequestMessage.timestamp()) //
152             .build();
153         String str = gson.toJson(dmaapResponseMessage);
154         return Mono.just(str);
155
156     }
157 }