dc979de080836dc66a6c3cc0310bdfb042af5f6b
[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.io.IOException;
28 import java.util.Optional;
29
30 import org.onap.dmaap.mr.client.MRBatchingPublisher;
31 import org.oransc.policyagent.clients.AsyncRestClient;
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 reactor.core.publisher.Mono;
37
38 public class DmaapMessageHandler {
39
40     private static final Logger logger = LoggerFactory.getLogger(DmaapMessageHandler.class);
41
42     private static Gson gson = new GsonBuilder() //
43         .create(); //
44
45     private final MRBatchingPublisher dmaapClient;
46     private final AsyncRestClient agentClient;
47
48     public DmaapMessageHandler(MRBatchingPublisher dmaapClient, AsyncRestClient agentClient) {
49         this.agentClient = agentClient;
50         this.dmaapClient = dmaapClient;
51     }
52
53     public void handleDmaapMsg(String msg) {
54         this.createTask(msg) //
55             .subscribe(message -> logger.debug("handleDmaapMsg: {}", message), //
56                 throwable -> logger.warn("handleDmaapMsg failure ", throwable), //
57                 () -> logger.debug("handleDmaapMsg complete"));
58     }
59
60     Mono<String> createTask(String msg) {
61         try {
62             DmaapRequestMessage dmaapRequestMessage = gson.fromJson(msg, ImmutableDmaapRequestMessage.class);
63
64             return this.invokePolicyAgent(dmaapRequestMessage) //
65                 .onErrorResume(t -> handleAgentCallError(t, msg, dmaapRequestMessage)) //
66                 .flatMap(response -> sendDmaapResponse(response, dmaapRequestMessage, HttpStatus.OK));
67
68         } catch (Exception e) {
69             logger.warn("Received unparsable message from DMAAP: {}", msg);
70             return Mono.error(e);
71         }
72     }
73
74     private Mono<String> handleAgentCallError(Throwable t, String origianalMessage,
75         DmaapRequestMessage dmaapRequestMessage) {
76         logger.debug("Agent call failed: {}", t.getMessage());
77         if (t instanceof ServiceException) {
78             String errorMessage = prepareBadOperationErrorMessage(t, origianalMessage);
79             return sendDmaapResponse(errorMessage, dmaapRequestMessage, HttpStatus.NOT_FOUND) //
80                 .flatMap(notUsed -> Mono.empty());
81         } else {
82             return sendDmaapResponse(t.toString(), dmaapRequestMessage, HttpStatus.NOT_FOUND) //
83                 .flatMap(notUsed -> Mono.empty());
84         }
85     }
86
87     private String prepareBadOperationErrorMessage(Throwable t, String origianalMessage) {
88         String badOperation = origianalMessage.substring(origianalMessage.indexOf("operation\":\"") + 12,
89             origianalMessage.indexOf(",\"url\":"));
90         String errorMessage = t.getMessage().replace("null", badOperation);
91         return errorMessage;
92     }
93
94     private Mono<String> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
95         DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
96         if (operation == null) {
97             return Mono.error(new ServiceException("Not implemented operation: " + operation));
98         }
99         Mono<String> result = null;
100         String uri = dmaapRequestMessage.url();
101         switch (operation) {
102             case DELETE:
103                 result = agentClient.delete(uri);
104                 break;
105             case GET:
106                 result = agentClient.get(uri);
107                 break;
108             case PUT:
109                 result = agentClient.put(uri, payload(dmaapRequestMessage));
110                 break;
111             case POST:
112                 result = agentClient.post(uri, payload(dmaapRequestMessage));
113                 break;
114             default:
115                 // Nothing, can never get here.
116         }
117         return result;
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 getDmaapResponseMessage(dmaapRequestMessage, response, status) //
133             .flatMap(this::sendToDmaap) //
134             .onErrorResume(this::handleResponseCallError);
135     }
136
137     private Mono<String> sendToDmaap(String body) {
138         try {
139             logger.debug("sendToDmaap: {} ", body);
140             dmaapClient.send(body);
141             dmaapClient.sendBatchWithResponse();
142             return Mono.just("OK");
143         } catch (IOException e) {
144             return Mono.error(e);
145         }
146     }
147
148     private Mono<String> handleResponseCallError(Throwable t) {
149         logger.debug("Failed to send respons to DMaaP: {}", t.getMessage());
150         return Mono.empty();
151     }
152
153     private Mono<String> getDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
154         HttpStatus status) {
155         DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
156             .status(status.toString()) //
157             .message(response) //
158             .type("response") //
159             .correlationId(dmaapRequestMessage.correlationId()) //
160             .originatorId(dmaapRequestMessage.originatorId()) //
161             .requestId(dmaapRequestMessage.requestId()) //
162             .timestamp(dmaapRequestMessage.timestamp()) //
163             .build();
164         String str = gson.toJson(dmaapResponseMessage);
165
166         return Mono.just(str);
167
168     }
169 }