Fixed concurrency problems
[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         .serializeNulls() //
42         .create(); //
43
44     private final MRBatchingPublisher dmaapClient;
45     private final AsyncRestClient agentClient;
46
47     public DmaapMessageHandler(MRBatchingPublisher dmaapClient, AsyncRestClient agentClient) {
48         this.agentClient = agentClient;
49         this.dmaapClient = dmaapClient;
50     }
51
52     public void handleDmaapMsg(String msg) {
53         this.createTask(msg) //
54             .subscribe(message -> logger.debug("handleDmaapMsg: {}", message), //
55                 throwable -> logger.warn("handleDmaapMsg failure ", throwable), //
56                 () -> logger.debug("handleDmaapMsg complete"));
57     }
58
59     Mono<String> createTask(String msg) {
60         try {
61             DmaapRequestMessage dmaapRequestMessage = gson.fromJson(msg, ImmutableDmaapRequestMessage.class);
62
63             return this.invokePolicyAgent(dmaapRequestMessage) //
64                 .onErrorResume(t -> handleAgentCallError(t, dmaapRequestMessage)) //
65                 .flatMap(response -> sendDmaapResponse(response, dmaapRequestMessage, HttpStatus.OK));
66
67         } catch (Exception e) {
68             logger.warn("Received unparsable message from DMAAP: {}", msg);
69             return Mono.error(e);
70         }
71     }
72
73     private Mono<String> handleAgentCallError(Throwable t, DmaapRequestMessage dmaapRequestMessage) {
74         logger.debug("Agent call failed: {}", t.getMessage());
75         return sendDmaapResponse(t.toString(), dmaapRequestMessage, HttpStatus.NOT_FOUND) //
76             .flatMap(notUsed -> Mono.empty());
77     }
78
79     private Mono<String> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
80         DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
81         Mono<String> result = null;
82         String uri = dmaapRequestMessage.url();
83         if (operation == Operation.DELETE) {
84             result = agentClient.delete(uri);
85         } else if (operation == Operation.GET) {
86             result = agentClient.get(uri);
87         } else if (operation == Operation.PUT) {
88             result = agentClient.put(uri, dmaapRequestMessage.payload());
89         } else if (operation == Operation.POST) {
90             result = agentClient.post(uri, dmaapRequestMessage.payload());
91         } else {
92             return Mono.error(new Exception("Not implemented operation: " + operation));
93         }
94         return result;
95     }
96
97     private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
98         HttpStatus status) {
99         return getDmaapResponseMessage(dmaapRequestMessage, response, status) //
100             .flatMap(this::sendToDmaap) //
101             .onErrorResume(this::handleResponseCallError);
102     }
103
104     private Mono<String> sendToDmaap(String body) {
105         try {
106             logger.debug("sendToDmaap: {} ", body);
107             dmaapClient.send(body);
108             dmaapClient.sendBatchWithResponse();
109             return Mono.just("OK");
110         } catch (IOException e) {
111             return Mono.error(e);
112         }
113     }
114
115     private Mono<String> handleResponseCallError(Throwable t) {
116         logger.debug("Failed to respond: {}", t.getMessage());
117         return Mono.empty();
118     }
119
120     private Mono<String> getDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
121         HttpStatus status) {
122         DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
123             .status(status.toString()) //
124             .message(response) //
125             .type("response") //
126             .correlationId(dmaapRequestMessage.correlationId()) //
127             .originatorId(dmaapRequestMessage.originatorId()) //
128             .requestId(dmaapRequestMessage.requestId()) //
129             .timestamp(dmaapRequestMessage.timestamp()) //
130             .build();
131         String str = gson.toJson(dmaapResponseMessage);
132
133         return Mono.just(str);
134
135     }
136 }