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