Changed the Dmaap message payload
[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
26 import java.io.IOException;
27
28 import org.onap.dmaap.mr.client.MRBatchingPublisher;
29 import org.oransc.policyagent.clients.AsyncRestClient;
30 import org.oransc.policyagent.dmaap.DmaapRequestMessage.Operation;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.springframework.http.HttpStatus;
34 import reactor.core.publisher.Mono;
35
36 public class DmaapMessageHandler {
37
38     private static final Logger logger = LoggerFactory.getLogger(DmaapMessageHandler.class);
39
40     private static Gson gson = new GsonBuilder() //
41         .create(); //
42
43     private final MRBatchingPublisher dmaapClient;
44     private final AsyncRestClient agentClient;
45
46     public DmaapMessageHandler(MRBatchingPublisher dmaapClient, AsyncRestClient agentClient) {
47         this.agentClient = agentClient;
48         this.dmaapClient = dmaapClient;
49     }
50
51     public void handleDmaapMsg(String msg) {
52         this.createTask(msg) //
53             .subscribe(message -> logger.debug("handleDmaapMsg: {}", message), //
54                 throwable -> logger.warn("handleDmaapMsg failure ", throwable), //
55                 () -> logger.debug("handleDmaapMsg complete"));
56     }
57
58     Mono<String> createTask(String msg) {
59         try {
60             DmaapRequestMessage dmaapRequestMessage = gson.fromJson(msg, ImmutableDmaapRequestMessage.class);
61
62             return this.invokePolicyAgent(dmaapRequestMessage) //
63                 .onErrorResume(t -> handleAgentCallError(t, dmaapRequestMessage)) //
64                 .flatMap(response -> sendDmaapResponse(response, dmaapRequestMessage, HttpStatus.OK));
65
66         } catch (Exception e) {
67             logger.warn("Received unparsable message from DMAAP: {}", msg);
68             return Mono.error(e);
69         }
70     }
71
72     private Mono<String> handleAgentCallError(Throwable t, DmaapRequestMessage dmaapRequestMessage) {
73         logger.debug("Agent call failed: {}", t.getMessage());
74         return sendDmaapResponse(t.toString(), dmaapRequestMessage, HttpStatus.NOT_FOUND) //
75             .flatMap(notUsed -> Mono.empty());
76     }
77
78     private Mono<String> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
79         DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
80         Mono<String> result = null;
81         String uri = dmaapRequestMessage.url();
82         if (operation == Operation.DELETE) {
83             result = agentClient.delete(uri);
84         } else if (operation == Operation.GET) {
85             result = agentClient.get(uri);
86         } else if (operation == Operation.PUT) {
87             result = agentClient.put(uri, payload(dmaapRequestMessage));
88         } else if (operation == Operation.POST) {
89             result = agentClient.post(uri, payload(dmaapRequestMessage));
90         } else {
91             return Mono.error(new Exception("Not implemented operation: " + operation));
92         }
93         return result;
94     }
95
96     private String payload(DmaapRequestMessage message) {
97         if (message.payload().isPresent()) {
98             return gson.toJson(message.payload().get());
99         } else {
100             logger.warn("Expected payload in message from DMAAP: {}", message);
101             return "";
102         }
103     }
104
105     private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
106         HttpStatus status) {
107         return getDmaapResponseMessage(dmaapRequestMessage, response, status) //
108             .flatMap(this::sendToDmaap) //
109             .onErrorResume(this::handleResponseCallError);
110     }
111
112     private Mono<String> sendToDmaap(String body) {
113         try {
114             logger.debug("sendToDmaap: {} ", body);
115             dmaapClient.send(body);
116             dmaapClient.sendBatchWithResponse();
117             return Mono.just("OK");
118         } catch (IOException e) {
119             return Mono.error(e);
120         }
121     }
122
123     private Mono<String> handleResponseCallError(Throwable t) {
124         logger.debug("Failed to respond: {}", t.getMessage());
125         return Mono.empty();
126     }
127
128     private Mono<String> getDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
129         HttpStatus status) {
130         DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
131             .status(status.toString()) //
132             .message(response) //
133             .type("response") //
134             .correlationId(dmaapRequestMessage.correlationId()) //
135             .originatorId(dmaapRequestMessage.originatorId()) //
136             .requestId(dmaapRequestMessage.requestId()) //
137             .timestamp(dmaapRequestMessage.timestamp()) //
138             .build();
139         String str = gson.toJson(dmaapResponseMessage);
140
141         return Mono.just(str);
142
143     }
144 }