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.WebClientResponseException;
39 import reactor.core.publisher.Mono;
42 * The class handles incoming requests from DMAAP.
44 * That means: invoke a REST call towards this services and to send back a
45 * response though DMAAP
47 public class DmaapMessageHandler {
48 private static final Logger logger = LoggerFactory.getLogger(DmaapMessageHandler.class);
49 private static Gson gson = new GsonBuilder() //
51 private final MRBatchingPublisher dmaapClient;
52 private final AsyncRestClient agentClient;
54 public DmaapMessageHandler(MRBatchingPublisher dmaapClient, AsyncRestClient agentClient) {
55 this.agentClient = agentClient;
56 this.dmaapClient = dmaapClient;
59 public void handleDmaapMsg(String msg) {
61 String result = this.createTask(msg).block();
62 logger.debug("handleDmaapMsg: {}", result);
63 } catch (Exception throwable) {
64 logger.warn("handleDmaapMsg failure {}", throwable.getMessage());
68 Mono<String> createTask(String msg) {
70 DmaapRequestMessage dmaapRequestMessage = gson.fromJson(msg, ImmutableDmaapRequestMessage.class);
71 return this.invokePolicyAgent(dmaapRequestMessage) //
72 .onErrorResume(t -> handleAgentCallError(t, msg, dmaapRequestMessage)) //
74 response -> sendDmaapResponse(response.getBody(), dmaapRequestMessage, response.getStatusCode()));
75 } catch (Exception e) {
76 logger.warn("Received unparsable message from DMAAP: {}", msg);
77 return Mono.error(e); // Cannot make any response
81 private Mono<ResponseEntity<String>> handleAgentCallError(Throwable t, String originalMessage,
82 DmaapRequestMessage dmaapRequestMessage) {
83 logger.debug("Agent call failed: {}", t.getMessage());
84 HttpStatus status = HttpStatus.NOT_FOUND;
85 String errorMessage = t.getMessage();
86 if (t instanceof WebClientResponseException) {
87 WebClientResponseException exception = (WebClientResponseException) t;
88 status = exception.getStatusCode();
89 errorMessage = exception.getResponseBodyAsString();
90 } else if (t instanceof ServiceException) {
91 status = HttpStatus.BAD_REQUEST;
92 errorMessage = prepareBadOperationErrorMessage(t, originalMessage);
95 return sendDmaapResponse(errorMessage, dmaapRequestMessage, status) //
96 .flatMap(notUsed -> Mono.empty());
99 private String prepareBadOperationErrorMessage(Throwable t, String originalMessage) {
100 String operationParameterStart = "operation\":\"";
101 int indexOfOperationStart = originalMessage.indexOf(operationParameterStart) + operationParameterStart.length();
102 int indexOfOperationEnd = originalMessage.indexOf("\",\"", indexOfOperationStart);
103 String badOperation = originalMessage.substring(indexOfOperationStart, indexOfOperationEnd);
104 return t.getMessage().replace("null", badOperation);
107 private Mono<ResponseEntity<String>> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
108 DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
109 String uri = dmaapRequestMessage.url();
111 if (operation == Operation.DELETE) {
112 return agentClient.deleteForEntity(uri);
113 } else if (operation == Operation.GET) {
114 return agentClient.getForEntity(uri);
115 } else if (operation == Operation.PUT) {
116 return agentClient.putForEntity(uri, payload(dmaapRequestMessage));
117 } else if (operation == Operation.POST) {
118 return agentClient.postForEntity(uri, payload(dmaapRequestMessage));
120 return Mono.error(new ServiceException("Not implemented operation: " + operation));
125 private String payload(DmaapRequestMessage message) {
126 Optional<JsonObject> payload = message.payload();
127 if (payload.isPresent()) {
128 return gson.toJson(payload.get());
130 logger.warn("Expected payload in message from DMAAP: {}", message);
135 private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
137 return createDmaapResponseMessage(dmaapRequestMessage, response, status) //
138 .flatMap(this::sendToDmaap) //
139 .onErrorResume(this::handleResponseCallError);
142 private Mono<String> sendToDmaap(String body) {
144 logger.debug("sendToDmaap: {} ", body);
145 dmaapClient.send(body);
146 dmaapClient.sendBatchWithResponse();
147 return Mono.just("OK");
148 } catch (IOException e) {
149 return Mono.error(e);
153 private Mono<String> handleResponseCallError(Throwable t) {
154 logger.debug("Failed to send response to DMaaP: {}", t.getMessage());
158 private Mono<String> createDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
160 DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
161 .status(status.toString()) //
162 .message(response == null ? "" : response) //
164 .correlationId(dmaapRequestMessage.correlationId() == null ? "" : dmaapRequestMessage.correlationId()) //
165 .originatorId(dmaapRequestMessage.originatorId() == null ? "" : dmaapRequestMessage.originatorId()) //
166 .requestId(dmaapRequestMessage.requestId() == null ? "" : dmaapRequestMessage.requestId()) //
167 .timestamp(dmaapRequestMessage.timestamp() == null ? "" : dmaapRequestMessage.timestamp()) //
169 String str = gson.toJson(dmaapResponseMessage);
170 return Mono.just(str);