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) {
59 this.createTask(msg) //
60 .subscribe(message -> logger.debug("handleDmaapMsg: {}", message), //
61 throwable -> logger.warn("handleDmaapMsg failure ", throwable), //
62 () -> logger.debug("handleDmaapMsg complete"));
65 Mono<String> createTask(String msg) {
67 DmaapRequestMessage dmaapRequestMessage = gson.fromJson(msg, ImmutableDmaapRequestMessage.class);
68 return this.invokePolicyAgent(dmaapRequestMessage) //
69 .onErrorResume(t -> handleAgentCallError(t, dmaapRequestMessage)) //
72 response -> sendDmaapResponse(response.getBody(), dmaapRequestMessage, response.getStatusCode()));
73 } catch (Exception e) {
74 logger.warn("Received unparsable message from DMAAP: {}", msg);
75 return Mono.error(e); // Cannot make any response
79 private Mono<ResponseEntity<String>> handleAgentCallError(Throwable t, DmaapRequestMessage dmaapRequestMessage) {
80 logger.debug("Agent call failed: {}", t.getMessage());
81 HttpStatus status = HttpStatus.NOT_FOUND;
82 String errorMessage = t.getMessage();
83 if (t instanceof WebClientResponseException) {
84 WebClientResponseException exception = (WebClientResponseException) t;
85 status = exception.getStatusCode();
86 errorMessage = exception.getResponseBodyAsString();
88 return sendDmaapResponse(errorMessage, dmaapRequestMessage, status) //
89 .flatMap(notUsed -> Mono.empty());
92 private Mono<ResponseEntity<String>> invokePolicyAgent(DmaapRequestMessage dmaapRequestMessage) {
93 DmaapRequestMessage.Operation operation = dmaapRequestMessage.operation();
95 String uri = dmaapRequestMessage.url();
96 if (operation == Operation.DELETE) {
97 return agentClient.deleteForEntity(uri);
98 } else if (operation == Operation.GET) {
99 return agentClient.getForEntity(uri);
100 } else if (operation == Operation.PUT) {
101 return agentClient.putForEntity(uri, payload(dmaapRequestMessage));
102 } else if (operation == Operation.POST) {
103 return agentClient.postForEntity(uri, payload(dmaapRequestMessage));
105 return Mono.error(new ServiceException("Not implemented operation: " + operation));
110 private String payload(DmaapRequestMessage message) {
111 Optional<JsonObject> payload = message.payload();
112 if (payload.isPresent()) {
113 return gson.toJson(payload.get());
115 logger.warn("Expected payload in message from DMAAP: {}", message);
120 private Mono<String> sendDmaapResponse(String response, DmaapRequestMessage dmaapRequestMessage,
122 return createDmaapResponseMessage(dmaapRequestMessage, response, status) //
123 .flatMap(this::sendToDmaap) //
124 .onErrorResume(this::handleResponseCallError);
127 private Mono<String> sendToDmaap(String body) {
129 logger.debug("sendToDmaap: {} ", body);
130 dmaapClient.send(body);
131 dmaapClient.sendBatchWithResponse();
132 return Mono.just("OK");
133 } catch (IOException e) {
134 return Mono.error(e);
138 private Mono<String> handleResponseCallError(Throwable t) {
139 logger.debug("Failed to respond: {}", t.getMessage());
143 private Mono<String> createDmaapResponseMessage(DmaapRequestMessage dmaapRequestMessage, String response,
145 DmaapResponseMessage dmaapResponseMessage = ImmutableDmaapResponseMessage.builder() //
146 .status(status.toString()) //
147 .message(response) //
149 .correlationId(dmaapRequestMessage.correlationId()) //
150 .originatorId(dmaapRequestMessage.originatorId()) //
151 .requestId(dmaapRequestMessage.requestId()) //
152 .timestamp(dmaapRequestMessage.timestamp()) //
154 String str = gson.toJson(dmaapResponseMessage);
155 return Mono.just(str);