2 * ========================LICENSE_START=================================
5 * Copyright (C) 2020 Nordix Foundation
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package org.oransc.policyagent.dmaap;
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.JsonObject;
27 import java.io.IOException;
28 import java.util.Optional;
30 import org.onap.dmaap.mr.client.MRBatchingPublisher;
31 import org.oransc.policyagent.clients.AsyncRestClient;
32 import org.oransc.policyagent.dmaap.DmaapRequestMessage.Operation;
33 import org.oransc.policyagent.exceptions.ServiceException;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.springframework.http.HttpStatus;
37 import org.springframework.http.ResponseEntity;
38 import org.springframework.web.reactive.function.client.WebClientException;
39 import org.springframework.web.reactive.function.client.WebClientResponseException;
40 import reactor.core.publisher.Mono;
43 * The class handles incoming requests from DMAAP.
45 * That means: invoke a REST call towards this services and to send back a
46 * response though DMAAP
48 public class DmaapMessageHandler {
49 private static final Logger logger = LoggerFactory.getLogger(DmaapMessageHandler.class);
50 private static Gson gson = new GsonBuilder() //
52 private final MRBatchingPublisher dmaapClient;
53 private final AsyncRestClient agentClient;
55 public DmaapMessageHandler(MRBatchingPublisher dmaapClient, AsyncRestClient agentClient) {
56 this.agentClient = agentClient;
57 this.dmaapClient = dmaapClient;
60 public void handleDmaapMsg(String msg) {
62 String result = this.createTask(msg).block();
63 logger.debug("handleDmaapMsg: {}", result);
64 } catch (Exception throwable) {
65 logger.warn("handleDmaapMsg failure {}", throwable.getMessage());
69 Mono<String> createTask(String msg) {
71 DmaapRequestMessage dmaapRequestMessage = gson.fromJson(msg, ImmutableDmaapRequestMessage.class);
72 return this.invokePolicyAgent(dmaapRequestMessage) //
73 .onErrorResume(t -> handleAgentCallError(t, msg, dmaapRequestMessage)) //
75 response -> sendDmaapResponse(response.getBody(), dmaapRequestMessage, response.getStatusCode()));
76 } catch (Exception e) {
77 String errorMsg = "Received unparsable message from DMAAP: \"" + msg + "\", reason: " + e.getMessage();
78 return Mono.error(new ServiceException(errorMsg)); // Cannot make any response
82 private Mono<ResponseEntity<String>> handleAgentCallError(Throwable t, String originalMessage,
83 DmaapRequestMessage dmaapRequestMessage) {
84 logger.debug("Agent call failed: {}", t.getMessage());
85 HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
86 String errorMessage = t.getMessage();
87 if (t instanceof WebClientResponseException) {
88 WebClientResponseException exception = (WebClientResponseException) t;
89 status = exception.getStatusCode();
90 errorMessage = exception.getResponseBodyAsString();
91 } else if (t instanceof ServiceException) {
92 status = HttpStatus.BAD_REQUEST;
93 errorMessage = prepareBadOperationErrorMessage(t, originalMessage);
94 } else if (!(t instanceof WebClientException)) {
95 logger.warn("Unexpected exception ", t);
97 return sendDmaapResponse(errorMessage, dmaapRequestMessage, status) //
98 .flatMap(notUsed -> Mono.empty());
101 private String prepareBadOperationErrorMessage(Throwable t, String originalMessage) {
102 String operationParameterStart = "operation\":\"";
103 int indexOfOperationStart = originalMessage.indexOf(operationParameterStart) + operationParameterStart.length();
104 int indexOfOperationEnd = originalMessage.indexOf("\",\"", indexOfOperationStart);
105 String badOperation = originalMessage.substring(indexOfOperationStart, indexOfOperationEnd);
106 return t.getMessage().replace("null", badOperation);
109 private Mono<ResponseEntity<String>> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
110 DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
111 String uri = dmaapRequestMessage.url();
113 if (operation == Operation.DELETE) {
114 return agentClient.deleteForEntity(uri);
115 } else if (operation == Operation.GET) {
116 return agentClient.getForEntity(uri);
117 } else if (operation == Operation.PUT) {
118 return agentClient.putForEntity(uri, payload(dmaapRequestMessage));
119 } else if (operation == Operation.POST) {
120 return agentClient.postForEntity(uri, payload(dmaapRequestMessage));
122 return Mono.error(new ServiceException("Not implemented operation: " + operation));
126 private String payload(DmaapRequestMessage message) {
127 Optional<JsonObject> payload = message.payload();
128 if (payload.isPresent()) {
129 return gson.toJson(payload.get());
131 logger.warn("Expected payload in message from DMAAP: {}", message);
136 private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
138 return createDmaapResponseMessage(dmaapRequestMessage, response, status) //
139 .flatMap(this::sendToDmaap) //
140 .onErrorResume(this::handleResponseCallError);
143 private Mono<String> sendToDmaap(String body) {
145 logger.debug("sendToDmaap: {} ", body);
146 dmaapClient.send(body);
147 dmaapClient.sendBatchWithResponse();
148 return Mono.just("OK");
149 } catch (IOException e) {
150 return Mono.error(e);
154 private Mono<String> handleResponseCallError(Throwable t) {
155 logger.debug("Failed to send response to DMaaP: {}", t.getMessage());
159 private Mono<String> createDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
161 DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
162 .status(status.toString()) //
163 .message(response == null ? "" : response) //
165 .correlationId(dmaapRequestMessage.correlationId() == null ? "" : dmaapRequestMessage.correlationId()) //
166 .originatorId(dmaapRequestMessage.originatorId() == null ? "" : dmaapRequestMessage.originatorId()) //
167 .requestId(dmaapRequestMessage.requestId() == null ? "" : dmaapRequestMessage.requestId()) //
168 .timestamp(dmaapRequestMessage.timestamp() == null ? "" : dmaapRequestMessage.timestamp()) //
170 String str = gson.toJson(dmaapResponseMessage);
171 return Mono.just(str);