2d7b5063844b99b318aaf5da55b280654db63577
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2020 Nordix Foundation. All rights reserved.
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.onap.ccsdk.oran.a1policymanagementservice.dmaap;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.JsonObject;
26
27 import java.util.Optional;
28
29 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
30 import org.onap.ccsdk.oran.a1policymanagementservice.dmaap.DmaapRequestMessage.Operation;
31 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.springframework.http.HttpStatus;
35 import org.springframework.http.ResponseEntity;
36 import org.springframework.web.reactive.function.client.WebClientException;
37 import org.springframework.web.reactive.function.client.WebClientResponseException;
38 import reactor.core.publisher.Mono;
39
40 /**
41  * The class handles incoming requests from DMAAP.
42  * <p>
43  * That means: invoke a REST call towards this services and to send back a
44  * response though DMAAP
45  */
46 public class DmaapMessageHandler {
47     private static final Logger logger = LoggerFactory.getLogger(DmaapMessageHandler.class);
48     private static Gson gson = new GsonBuilder().create();
49     private final AsyncRestClient dmaapClient;
50     private final AsyncRestClient pmsClient;
51
52     public DmaapMessageHandler(AsyncRestClient dmaapClient, AsyncRestClient pmsClient) {
53         this.pmsClient = pmsClient;
54         this.dmaapClient = dmaapClient;
55     }
56
57     public void handleDmaapMsg(DmaapRequestMessage msg) {
58         try {
59             String result = this.createTask(msg).block();
60             logger.debug("handleDmaapMsg: {}", result);
61         } catch (Exception throwable) {
62             logger.warn("handleDmaapMsg failure {}", throwable.getMessage());
63         }
64     }
65
66     Mono<String> createTask(DmaapRequestMessage dmaapRequestMessage) {
67         return this.invokePolicyManagementService(dmaapRequestMessage) //
68             .onErrorResume(t -> handlePolicyManagementServiceCallError(t, dmaapRequestMessage)) //
69             .flatMap(response -> sendDmaapResponse(response.getBody(), dmaapRequestMessage, response.getStatusCode()));
70     }
71
72     private Mono<ResponseEntity<String>> handlePolicyManagementServiceCallError(Throwable error,
73         DmaapRequestMessage dmaapRequestMessage) {
74         logger.debug("Policy Management Service call failed: {}", error.getMessage());
75         HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
76         String errorMessage = error.getMessage();
77         if (error instanceof WebClientResponseException) {
78             WebClientResponseException exception = (WebClientResponseException) error;
79             status = exception.getStatusCode();
80             errorMessage = exception.getResponseBodyAsString();
81         } else if (error instanceof ServiceException) {
82             status = HttpStatus.BAD_REQUEST;
83             errorMessage = error.getMessage();
84         } else if (!(error instanceof WebClientException)) {
85             logger.warn("Unexpected exception ", error);
86         }
87         return sendDmaapResponse(errorMessage, dmaapRequestMessage, status) //
88             .flatMap(notUsed -> Mono.empty());
89     }
90
91     public Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage, HttpStatus status) {
92         return createDmaapResponseMessage(dmaapRequestMessage, response, status) //
93             .flatMap(this::sendToDmaap) //
94             .onErrorResume(this::handleResponseCallError);
95     }
96
97     private Mono<ResponseEntity<String>> invokePolicyManagementService(DmaapRequestMessage dmaapRequestMessage) {
98         DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
99         String uri = dmaapRequestMessage.url();
100
101         if (operation == Operation.DELETE) {
102             return pmsClient.deleteForEntity(uri);
103         } else if (operation == Operation.GET) {
104             return pmsClient.getForEntity(uri);
105         } else if (operation == Operation.PUT) {
106             return pmsClient.putForEntity(uri, payload(dmaapRequestMessage));
107         } else if (operation == Operation.POST) {
108             return pmsClient.postForEntity(uri, payload(dmaapRequestMessage));
109         } else {
110             return Mono.error(new ServiceException("Not implemented operation: " + operation));
111         }
112     }
113
114     private String payload(DmaapRequestMessage message) {
115         Optional<JsonObject> payload = message.payload();
116         if (payload.isPresent()) {
117             return gson.toJson(payload.get());
118         } else {
119             logger.warn("Expected payload in message from DMAAP: {}", message);
120             return "";
121         }
122     }
123
124     private Mono<String> sendToDmaap(String body) {
125         logger.debug("sendToDmaap: {} ", body);
126         return dmaapClient.post("", "[" + body + "]");
127     }
128
129     private Mono<String> handleResponseCallError(Throwable t) {
130         logger.warn("Failed to send response to DMaaP: {}", t.getMessage());
131         return Mono.empty();
132     }
133
134     private Mono<String> createDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
135         HttpStatus status) {
136         DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
137             .status(status.toString()) //
138             .message(response == null ? "" : response) //
139             .type("response") //
140             .correlationId(dmaapRequestMessage.correlationId() == null ? "" : dmaapRequestMessage.correlationId()) //
141             .originatorId(dmaapRequestMessage.originatorId() == null ? "" : dmaapRequestMessage.originatorId()) //
142             .requestId(dmaapRequestMessage.requestId() == null ? "" : dmaapRequestMessage.requestId()) //
143             .timestamp(dmaapRequestMessage.timestamp() == null ? "" : dmaapRequestMessage.timestamp()) //
144             .build();
145         String str = gson.toJson(dmaapResponseMessage);
146         return Mono.just(str);
147     }
148 }