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===================================
20 package org.oransc.policyagent.dmaap;
22 import com.google.gson.Gson;
23 import com.google.gson.GsonBuilder;
24 import com.google.gson.JsonObject;
26 import java.io.IOException;
27 import java.util.Optional;
29 import org.onap.dmaap.mr.client.MRBatchingPublisher;
30 import org.oransc.policyagent.clients.AsyncRestClient;
31 import org.oransc.policyagent.dmaap.DmaapRequestMessage.Operation;
32 import org.oransc.policyagent.exceptions.ServiceException;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.springframework.http.HttpStatus;
36 import org.springframework.http.ResponseEntity;
37 import org.springframework.web.reactive.function.client.WebClientResponseException;
38 import reactor.core.publisher.Mono;
41 * The class handles incoming requests from DMAAP.
43 * That means: invoke a REST call towards this services and to send back a
44 * response though DMAAP
46 public class DmaapMessageHandler {
47 private static final Logger logger = LoggerFactory.getLogger(DmaapMessageHandler.class);
48 private static Gson gson = new GsonBuilder() //
50 private final MRBatchingPublisher dmaapClient;
51 private final AsyncRestClient agentClient;
53 public DmaapMessageHandler(MRBatchingPublisher dmaapClient, AsyncRestClient agentClient) {
54 this.agentClient = agentClient;
55 this.dmaapClient = dmaapClient;
58 public void handleDmaapMsg(String msg) {
60 String result = this.createTask(msg).block();
61 logger.debug("handleDmaapMsg: {}", result);
62 } catch (Exception throwable) {
63 logger.warn("handleDmaapMsg failure {}", throwable.getMessage());
67 Mono<String> createTask(String msg) {
69 DmaapRequestMessage dmaapRequestMessage = gson.fromJson(msg, ImmutableDmaapRequestMessage.class);
70 return this.invokePolicyAgent(dmaapRequestMessage) //
71 .onErrorResume(t -> handleAgentCallError(t, msg, dmaapRequestMessage)) //
73 response -> sendDmaapResponse(response.getBody(), dmaapRequestMessage, response.getStatusCode()));
74 } catch (Exception e) {
75 logger.warn("Received unparsable message from DMAAP: {}", msg);
76 return Mono.error(e); // Cannot make any response
80 private Mono<ResponseEntity<String>> handleAgentCallError(Throwable t, String originalMessage,
81 DmaapRequestMessage dmaapRequestMessage) {
82 logger.debug("Agent call failed: {}", t.getMessage());
83 HttpStatus status = HttpStatus.NOT_FOUND;
84 String errorMessage = t.getMessage();
85 if (t instanceof WebClientResponseException) {
86 WebClientResponseException exception = (WebClientResponseException) t;
87 status = exception.getStatusCode();
88 errorMessage = exception.getResponseBodyAsString();
89 } else if (t instanceof ServiceException) {
90 status = HttpStatus.BAD_REQUEST;
91 errorMessage = prepareBadOperationErrorMessage(t, originalMessage);
94 return sendDmaapResponse(errorMessage, dmaapRequestMessage, status) //
95 .flatMap(notUsed -> Mono.empty());
98 private String prepareBadOperationErrorMessage(Throwable t, String originalMessage) {
99 String operationParameterStart = "operation\":\"";
100 int indexOfOperationStart = originalMessage.indexOf(operationParameterStart) + operationParameterStart.length();
101 int indexOfOperationEnd = originalMessage.indexOf("\",\"", indexOfOperationStart);
102 String badOperation = originalMessage.substring(indexOfOperationStart, indexOfOperationEnd);
103 return t.getMessage().replace("null", badOperation);
106 private Mono<ResponseEntity<String>> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
107 DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
108 String uri = dmaapRequestMessage.url();
110 if (operation == Operation.DELETE) {
111 return agentClient.deleteForEntity(uri);
112 } else if (operation == Operation.GET) {
113 return agentClient.getForEntity(uri);
114 } else if (operation == Operation.PUT) {
115 return agentClient.putForEntity(uri, payload(dmaapRequestMessage));
116 } else if (operation == Operation.POST) {
117 return agentClient.postForEntity(uri, payload(dmaapRequestMessage));
119 return Mono.error(new ServiceException("Not implemented operation: " + operation));
124 private String payload(DmaapRequestMessage message) {
125 Optional<JsonObject> payload = message.payload();
126 if (payload.isPresent()) {
127 return gson.toJson(payload.get());
129 logger.warn("Expected payload in message from DMAAP: {}", message);
134 private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
136 return createDmaapResponseMessage(dmaapRequestMessage, response, status) //
137 .flatMap(this::sendToDmaap) //
138 .onErrorResume(this::handleResponseCallError);
141 private Mono<String> sendToDmaap(String body) {
143 logger.debug("sendToDmaap: {} ", body);
144 dmaapClient.send(body);
145 dmaapClient.sendBatchWithResponse();
146 return Mono.just("OK");
147 } catch (IOException e) {
148 return Mono.error(e);
152 private Mono<String> handleResponseCallError(Throwable t) {
153 logger.debug("Failed to send response to DMaaP: {}", t.getMessage());
157 private Mono<String> createDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
159 DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
160 .status(status.toString()) //
161 .message(response == null ? "" : response) //
163 .correlationId(dmaapRequestMessage.correlationId() == null ? "" : dmaapRequestMessage.correlationId()) //
164 .originatorId(dmaapRequestMessage.originatorId() == null ? "" : dmaapRequestMessage.originatorId()) //
165 .requestId(dmaapRequestMessage.requestId() == null ? "" : dmaapRequestMessage.requestId()) //
166 .timestamp(dmaapRequestMessage.timestamp() == null ? "" : dmaapRequestMessage.timestamp()) //
168 String str = gson.toJson(dmaapResponseMessage);
169 return Mono.just(str);