Merge "Add unit tests for PolicyAgentApi in dashboard"
[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.dmaap.DmaapRequestMessage.Operation;
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, 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, DmaapRequestMessage dmaapRequestMessage) {
75         logger.debug("Agent call failed: {}", t.getMessage());
76         return sendDmaapResponse(t.toString(), dmaapRequestMessage, HttpStatus.NOT_FOUND) //
77             .flatMap(notUsed -> Mono.empty());
78     }
79
80     private Mono<String> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
81         DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
82         Mono<String> result = null;
83         String uri = dmaapRequestMessage.url();
84         if (operation == Operation.DELETE) {
85             result = agentClient.delete(uri);
86         } else if (operation == Operation.GET) {
87             result = agentClient.get(uri);
88         } else if (operation == Operation.PUT) {
89             result = agentClient.put(uri, payload(dmaapRequestMessage));
90         } else if (operation == Operation.POST) {
91             result = agentClient.post(uri, payload(dmaapRequestMessage));
92         } else {
93             return Mono.error(new Exception("Not implemented operation: " + operation));
94         }
95         return result;
96     }
97
98     private String payload(DmaapRequestMessage message) {
99         Optional<JsonObject> payload = message.payload();
100         if (payload.isPresent()) {
101             return gson.toJson(payload.get());
102         } else {
103             logger.warn("Expected payload in message from DMAAP: {}", message);
104             return "";
105         }
106     }
107
108     private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
109         HttpStatus status) {
110         return getDmaapResponseMessage(dmaapRequestMessage, response, status) //
111             .flatMap(this::sendToDmaap) //
112             .onErrorResume(this::handleResponseCallError);
113     }
114
115     private Mono<String> sendToDmaap(String body) {
116         try {
117             logger.debug("sendToDmaap: {} ", body);
118             dmaapClient.send(body);
119             dmaapClient.sendBatchWithResponse();
120             return Mono.just("OK");
121         } catch (IOException e) {
122             return Mono.error(e);
123         }
124     }
125
126     private Mono<String> handleResponseCallError(Throwable t) {
127         logger.debug("Failed to respond: {}", t.getMessage());
128         return Mono.empty();
129     }
130
131     private Mono<String> getDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
132         HttpStatus status) {
133         DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
134             .status(status.toString()) //
135             .message(response) //
136             .type("response") //
137             .correlationId(dmaapRequestMessage.correlationId()) //
138             .originatorId(dmaapRequestMessage.originatorId()) //
139             .requestId(dmaapRequestMessage.requestId()) //
140             .timestamp(dmaapRequestMessage.timestamp()) //
141             .build();
142         String str = gson.toJson(dmaapResponseMessage);
143
144         return Mono.just(str);
145
146     }
147 }