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 response though DMAAP
45 public class DmaapMessageHandler {
46 private static final Logger logger = LoggerFactory.getLogger(DmaapMessageHandler.class);
47 private static Gson gson = new GsonBuilder() //
49 private final AsyncRestClient dmaapClient;
50 private final AsyncRestClient agentClient;
52 public DmaapMessageHandler(AsyncRestClient dmaapClient, AsyncRestClient agentClient) {
53 this.agentClient = agentClient;
54 this.dmaapClient = dmaapClient;
57 public void handleDmaapMsg(String msg) {
59 String result = this.createTask(msg).block();
60 logger.debug("handleDmaapMsg: {}", result);
61 } catch (Exception throwable) {
62 logger.warn("handleDmaapMsg failure {}", throwable.getMessage());
66 Mono<String> createTask(String msg) {
68 DmaapRequestMessage dmaapRequestMessage = gson.fromJson(msg, ImmutableDmaapRequestMessage.class);
69 return this.invokePolicyAgent(dmaapRequestMessage) //
70 .onErrorResume(t -> handleAgentCallError(t, dmaapRequestMessage)) //
72 response -> sendDmaapResponse(response.getBody(), dmaapRequestMessage, response.getStatusCode()));
73 } catch (Exception e) {
74 String errorMsg = "Received unparsable message from DMAAP: \"" + msg + "\", reason: " + e.getMessage();
75 return Mono.error(new ServiceException(errorMsg)); // Cannot make any response
79 private Mono<ResponseEntity<String>> handleAgentCallError(Throwable error,
80 DmaapRequestMessage dmaapRequestMessage) {
81 logger.debug("Agent call failed: {}", error.getMessage());
82 HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
83 String errorMessage = error.getMessage();
84 if (error instanceof WebClientResponseException) {
85 WebClientResponseException exception = (WebClientResponseException) error;
86 status = exception.getStatusCode();
87 errorMessage = exception.getResponseBodyAsString();
88 } else if (error instanceof ServiceException) {
89 status = HttpStatus.BAD_REQUEST;
90 errorMessage = error.getMessage();
91 } else if (!(error instanceof WebClientException)) {
92 logger.warn("Unexpected exception ", error);
94 return sendDmaapResponse(errorMessage, dmaapRequestMessage, status) //
95 .flatMap(notUsed -> Mono.empty());
98 private Mono<ResponseEntity<String>> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
99 DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
100 String uri = dmaapRequestMessage.url();
102 if (operation == Operation.DELETE) {
103 return agentClient.deleteForEntity(uri);
104 } else if (operation == Operation.GET) {
105 return agentClient.getForEntity(uri);
106 } else if (operation == Operation.PUT) {
107 return agentClient.putForEntity(uri, payload(dmaapRequestMessage));
108 } else if (operation == Operation.POST) {
109 return agentClient.postForEntity(uri, payload(dmaapRequestMessage));
111 return Mono.error(new ServiceException("Not implemented operation: " + operation));
115 private String payload(DmaapRequestMessage message) {
116 Optional<JsonObject> payload = message.payload();
117 if (payload.isPresent()) {
118 return gson.toJson(payload.get());
120 logger.warn("Expected payload in message from DMAAP: {}", message);
125 private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
127 return createDmaapResponseMessage(dmaapRequestMessage, response, status) //
128 .flatMap(this::sendToDmaap) //
129 .onErrorResume(this::handleResponseCallError);
132 private Mono<String> sendToDmaap(String body) {
133 logger.debug("sendToDmaap: {} ", body);
134 return dmaapClient.post("", "[" + body + "]");
137 private Mono<String> handleResponseCallError(Throwable t) {
138 logger.debug("Failed to send response to DMaaP: {}", t.getMessage());
142 private Mono<String> createDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
144 DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
145 .status(status.toString()) //
146 .message(response == null ? "" : response) //
148 .correlationId(dmaapRequestMessage.correlationId() == null ? "" : dmaapRequestMessage.correlationId()) //
149 .originatorId(dmaapRequestMessage.originatorId() == null ? "" : dmaapRequestMessage.originatorId()) //
150 .requestId(dmaapRequestMessage.requestId() == null ? "" : dmaapRequestMessage.requestId()) //
151 .timestamp(dmaapRequestMessage.timestamp() == null ? "" : dmaapRequestMessage.timestamp()) //
153 String str = gson.toJson(dmaapResponseMessage);
154 return Mono.just(str);