Merge "Updated documentation and scripts using https between agent and MR"
[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
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 AsyncRestClient dmaapClient;
51     private final AsyncRestClient agentClient;
52
53     public DmaapMessageHandler(AsyncRestClient 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             String errorMsg = "Received unparsable message from DMAAP: \"" + msg + "\", reason: " + e.getMessage();
76             return Mono.error(new ServiceException(errorMsg)); // 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.INTERNAL_SERVER_ERROR;
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         } else if (!(t instanceof WebClientException)) {
93             logger.warn("Unexpected exception ", t);
94         }
95         return sendDmaapResponse(errorMessage, dmaapRequestMessage, status) //
96             .flatMap(notUsed -> Mono.empty());
97     }
98
99     private String prepareBadOperationErrorMessage(Throwable t, String originalMessage) {
100         return t.getMessage();
101     }
102
103     private Mono<ResponseEntity<String>> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
104         DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
105         String uri = dmaapRequestMessage.url();
106
107         if (operation == Operation.DELETE) {
108             return agentClient.deleteForEntity(uri);
109         } else if (operation == Operation.GET) {
110             return agentClient.getForEntity(uri);
111         } else if (operation == Operation.PUT) {
112             return agentClient.putForEntity(uri, payload(dmaapRequestMessage));
113         } else if (operation == Operation.POST) {
114             return agentClient.postForEntity(uri, payload(dmaapRequestMessage));
115         } else {
116             return Mono.error(new ServiceException("Not implemented operation: " + operation));
117         }
118     }
119
120     private String payload(DmaapRequestMessage message) {
121         Optional<JsonObject> payload = message.payload();
122         if (payload.isPresent()) {
123             return gson.toJson(payload.get());
124         } else {
125             logger.warn("Expected payload in message from DMAAP: {}", message);
126             return "";
127         }
128     }
129
130     private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
131         HttpStatus status) {
132         return createDmaapResponseMessage(dmaapRequestMessage, response, status) //
133             .flatMap(this::sendToDmaap) //
134             .onErrorResume(this::handleResponseCallError);
135     }
136
137     private Mono<String> sendToDmaap(String body) {
138         logger.debug("sendToDmaap: {} ", body);
139         return dmaapClient.post("", "[" + body + "]");
140     }
141
142     private Mono<String> handleResponseCallError(Throwable t) {
143         logger.debug("Failed to send response to DMaaP: {}", t.getMessage());
144         return Mono.empty();
145     }
146
147     private Mono<String> createDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
148         HttpStatus status) {
149         DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
150             .status(status.toString()) //
151             .message(response == null ? "" : response) //
152             .type("response") //
153             .correlationId(dmaapRequestMessage.correlationId() == null ? "" : dmaapRequestMessage.correlationId()) //
154             .originatorId(dmaapRequestMessage.originatorId() == null ? "" : dmaapRequestMessage.originatorId()) //
155             .requestId(dmaapRequestMessage.requestId() == null ? "" : dmaapRequestMessage.requestId()) //
156             .timestamp(dmaapRequestMessage.timestamp() == null ? "" : dmaapRequestMessage.timestamp()) //
157             .build();
158         String str = gson.toJson(dmaapResponseMessage);
159         return Mono.just(str);
160
161     }
162 }