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.util.Optional;
29 import org.oransc.policyagent.clients.AsyncRestClient;
30 import org.oransc.policyagent.dmaap.DmaapRequestMessage.Operation;
31 import org.oransc.policyagent.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;
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 AsyncRestClient dmaapClient;
51 private final AsyncRestClient agentClient;
53 public DmaapMessageHandler(AsyncRestClient 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 String errorMsg = "Received unparsable message from DMAAP: \"" + msg + "\", reason: " + e.getMessage();
76 return Mono.error(new ServiceException(errorMsg)); // 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.INTERNAL_SERVER_ERROR;
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);
92 } else if (!(t instanceof WebClientException)) {
93 logger.warn("Unexpected exception ", t);
95 return sendDmaapResponse(errorMessage, dmaapRequestMessage, status) //
96 .flatMap(notUsed -> Mono.empty());
99 private String prepareBadOperationErrorMessage(Throwable t, String originalMessage) {
100 return t.getMessage();
103 private Mono<ResponseEntity<String>> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
104 DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
105 String uri = dmaapRequestMessage.url();
107 if (operation == Operation.DELETE) {
108 return agentClient.deleteForEntity(uri);
109 } else if (operation == Operation.GET) {
110 return agentClient.getForEntity(uri);
111 } else if (operation == Operation.PUT) {
112 return agentClient.putForEntity(uri, payload(dmaapRequestMessage));
113 } else if (operation == Operation.POST) {
114 return agentClient.postForEntity(uri, payload(dmaapRequestMessage));
116 return Mono.error(new ServiceException("Not implemented operation: " + operation));
120 private String payload(DmaapRequestMessage message) {
121 Optional<JsonObject> payload = message.payload();
122 if (payload.isPresent()) {
123 return gson.toJson(payload.get());
125 logger.warn("Expected payload in message from DMAAP: {}", message);
130 private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
132 return createDmaapResponseMessage(dmaapRequestMessage, response, status) //
133 .flatMap(this::sendToDmaap) //
134 .onErrorResume(this::handleResponseCallError);
137 private Mono<String> sendToDmaap(String body) {
138 logger.debug("sendToDmaap: {} ", body);
139 return dmaapClient.post("", "[" + body + "]");
142 private Mono<String> handleResponseCallError(Throwable t) {
143 logger.debug("Failed to send response to DMaaP: {}", t.getMessage());
147 private Mono<String> createDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
149 DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
150 .status(status.toString()) //
151 .message(response == null ? "" : response) //
153 .correlationId(dmaapRequestMessage.correlationId() == null ? "" : dmaapRequestMessage.correlationId()) //
154 .originatorId(dmaapRequestMessage.originatorId() == null ? "" : dmaapRequestMessage.originatorId()) //
155 .requestId(dmaapRequestMessage.requestId() == null ? "" : dmaapRequestMessage.requestId()) //
156 .timestamp(dmaapRequestMessage.timestamp() == null ? "" : dmaapRequestMessage.timestamp()) //
158 String str = gson.toJson(dmaapResponseMessage);
159 return Mono.just(str);