Merge "REST error codes"
[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, dmaapRequestMessage)) //
70                 .flatMap(
71
72                     response -> sendDmaapResponse(response.getBody(), dmaapRequestMessage, response.getStatusCode()));
73         } catch (Exception e) {
74             logger.warn("Received unparsable message from DMAAP: {}", msg);
75             return Mono.error(e); // Cannot make any response
76         }
77     }
78
79     private Mono<ResponseEntity<String>> handleAgentCallError(Throwable t, 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         }
88         return sendDmaapResponse(errorMessage, dmaapRequestMessage, status) //
89             .flatMap(notUsed -> Mono.empty());
90     }
91
92     private Mono<ResponseEntity<String>> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
93         DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
94
95         String uri = dmaapRequestMessage.url();
96         if (operation == Operation.DELETE) {
97             return agentClient.deleteForEntity(uri);
98         } else if (operation == Operation.GET) {
99             return agentClient.getForEntity(uri);
100         } else if (operation == Operation.PUT) {
101             return agentClient.putForEntity(uri, payload(dmaapRequestMessage));
102         } else if (operation == Operation.POST) {
103             return agentClient.postForEntity(uri, payload(dmaapRequestMessage));
104         } else {
105             return Mono.error(new ServiceException("Not implemented operation: " + operation));
106         }
107
108     }
109
110     private String payload(DmaapRequestMessage message) {
111         Optional<JsonObject> payload = message.payload();
112         if (payload.isPresent()) {
113             return gson.toJson(payload.get());
114         } else {
115             logger.warn("Expected payload in message from DMAAP: {}", message);
116             return "";
117         }
118     }
119
120     private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
121         HttpStatus status) {
122         return createDmaapResponseMessage(dmaapRequestMessage, response, status) //
123             .flatMap(this::sendToDmaap) //
124             .onErrorResume(this::handleResponseCallError);
125     }
126
127     private Mono<String> sendToDmaap(String body) {
128         try {
129             logger.debug("sendToDmaap: {} ", body);
130             dmaapClient.send(body);
131             dmaapClient.sendBatchWithResponse();
132             return Mono.just("OK");
133         } catch (IOException e) {
134             return Mono.error(e);
135         }
136     }
137
138     private Mono<String> handleResponseCallError(Throwable t) {
139         logger.debug("Failed to respond: {}", t.getMessage());
140         return Mono.empty();
141     }
142
143     private Mono<String> createDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
144         HttpStatus status) {
145         DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
146             .status(status.toString()) //
147             .message(response) //
148             .type("response") //
149             .correlationId(dmaapRequestMessage.correlationId()) //
150             .originatorId(dmaapRequestMessage.originatorId()) //
151             .requestId(dmaapRequestMessage.requestId()) //
152             .timestamp(dmaapRequestMessage.timestamp()) //
153             .build();
154         String str = gson.toJson(dmaapResponseMessage);
155         return Mono.just(str);
156
157     }
158 }