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