2 * ========================LICENSE_START=================================
4 * ======================================================================
5 * Copyright (C) 2020 Nordix Foundation. All rights reserved.
6 * ======================================================================
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.onap.ccsdk.oran.a1policymanagementservice.dmaap;
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.JsonArray;
26 import com.google.gson.JsonElement;
27 import com.google.gson.JsonParser;
29 import java.time.Duration;
30 import java.util.ArrayList;
31 import java.util.List;
33 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
34 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
35 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.springframework.beans.factory.annotation.Autowired;
39 import org.springframework.beans.factory.annotation.Value;
40 import org.springframework.http.HttpStatus;
41 import org.springframework.stereotype.Component;
43 import reactor.core.publisher.Flux;
44 import reactor.core.publisher.FluxSink;
45 import reactor.core.publisher.Mono;
48 * The class fetches incoming requests from DMAAP. It uses the timeout parameter
49 * that lets the MessageRouter keep the connection with the Kafka open until
50 * requests are sent in.
53 * this service will regularly check the configuration and start polling DMaaP
54 * if the configuration is added. If the DMaaP configuration is removed, then
55 * the service will stop polling and resume checking for configuration.
58 * Each received request is processed by {@link DmaapMessageHandler}.
61 public class DmaapMessageConsumer {
63 protected static final Duration TIME_BETWEEN_DMAAP_RETRIES = Duration.ofSeconds(10);
65 private static final Logger logger = LoggerFactory.getLogger(DmaapMessageConsumer.class);
67 private final ApplicationConfig applicationConfig;
69 private DmaapMessageHandler dmaapMessageHandler = null;
71 private final Gson gson;
73 private final AsyncRestClientFactory restClientFactory;
75 private final InfiniteFlux infiniteSubmitter = new InfiniteFlux();
77 @Value("${server.http-port}")
78 private int localServerHttpPort;
80 private static class InfiniteFlux {
81 private FluxSink<Integer> sink;
82 private int counter = 0;
84 public synchronized Flux<Integer> start() {
86 return Flux.create(this::next).doOnRequest(this::onRequest);
89 public synchronized void stop() {
90 if (this.sink != null) {
96 void onRequest(long no) {
97 logger.debug("InfiniteFlux.onRequest {}", no);
98 for (long i = 0; i < no; ++i) {
103 void next(FluxSink<Integer> sink) {
104 logger.debug("InfiniteFlux.next");
106 sink.next(counter++);
112 public DmaapMessageConsumer(ApplicationConfig applicationConfig) {
113 this.applicationConfig = applicationConfig;
114 GsonBuilder gsonBuilder = new GsonBuilder();
115 this.gson = gsonBuilder.create();
116 this.restClientFactory = new AsyncRestClientFactory(applicationConfig.getWebClientConfig());
120 * Starts the DMAAP consumer. If there is a DMaaP configuration, it will start
121 * polling for messages. Otherwise it will check regularly for the
125 public void start() {
126 infiniteSubmitter.stop();
128 createTask().subscribe(//
129 value -> logger.debug("DmaapMessageConsumer next: {}", value), //
130 throwable -> logger.error("DmaapMessageConsumer error: {}", throwable.getMessage()), //
131 () -> logger.warn("DmaapMessageConsumer stopped") //
135 protected Flux<String> createTask() {
136 return infiniteFlux() //
137 .flatMap(notUsed -> fetchFromDmaap(), 1) //
138 .doOnNext(message -> logger.debug("Message Reveived from DMAAP : {}", message)) //
139 .flatMap(this::parseReceivedMessage, 1)//
140 .flatMap(this::handleDmaapMsg, 1) //
141 .onErrorResume(throwable -> Mono.empty());
144 protected Flux<Integer> infiniteFlux() {
145 return infiniteSubmitter.start();
148 protected Mono<Object> delay() {
149 return Mono.delay(TIME_BETWEEN_DMAAP_RETRIES).flatMap(o -> Mono.empty());
152 private <T> List<T> parseList(String jsonString, Class<T> clazz) {
153 List<T> result = new ArrayList<>();
154 JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
155 for (JsonElement jsonElement : jsonArr) {
156 // The element can either be a JsonObject or a JsonString
157 if (jsonElement.isJsonPrimitive()) {
158 T json = gson.fromJson(jsonElement.getAsString(), clazz);
161 T json = gson.fromJson(jsonElement.toString(), clazz);
168 protected boolean isDmaapConfigured() {
169 String producerTopicUrl = applicationConfig.getDmaapProducerTopicUrl();
170 String consumerTopicUrl = applicationConfig.getDmaapConsumerTopicUrl();
171 return (producerTopicUrl != null && consumerTopicUrl != null && !producerTopicUrl.isEmpty()
172 && !consumerTopicUrl.isEmpty());
175 protected Mono<String> handleDmaapMsg(DmaapRequestMessage dmaapRequestMessage) {
176 return getDmaapMessageHandler().handleDmaapMsg(dmaapRequestMessage);
179 protected Mono<String> getFromMessageRouter(String topicUrl) {
180 logger.trace("getFromMessageRouter {}", topicUrl);
181 AsyncRestClient c = restClientFactory.createRestClientNoHttpProxy("");
182 return c.get(topicUrl);
185 protected Flux<DmaapRequestMessage> parseReceivedMessage(String jsonString) {
187 logger.trace("parseMessages {}", jsonString);
188 return Flux.fromIterable(parseList(jsonString, DmaapRequestMessage.class));
189 } catch (Exception e) {
190 logger.error("parseMessages error {}", jsonString);
191 return sendErrorResponse("Could not parse: " + jsonString) //
192 .flatMapMany(s -> Flux.empty());
196 protected Mono<String> sendErrorResponse(String response) {
197 logger.debug("sendErrorResponse {}", response);
198 DmaapRequestMessage fakeRequest = DmaapRequestMessage.builder() //
200 .correlationId("") //
201 .operation(DmaapRequestMessage.Operation.PUT) //
209 return getDmaapMessageHandler().sendDmaapResponse(response, fakeRequest, HttpStatus.BAD_REQUEST) //
210 .onErrorResume(e -> Mono.empty());
213 private Mono<String> fetchFromDmaap() {
214 if (!this.isDmaapConfigured()) {
215 logger.debug("fetchFromDmaap, no action DMAAP not configured");
216 return delay().flatMap(o -> Mono.empty());
218 logger.debug("fetchFromDmaap");
219 String topicUrl = this.applicationConfig.getDmaapConsumerTopicUrl();
221 return getFromMessageRouter(topicUrl) //
222 .onErrorResume(throwable -> delay().flatMap(o -> Mono.empty()));
225 private DmaapMessageHandler getDmaapMessageHandler() {
226 if (this.dmaapMessageHandler == null) {
227 String pmsBaseUrl = "http://localhost:" + this.localServerHttpPort;
228 AsyncRestClient pmsClient = restClientFactory.createRestClientNoHttpProxy(pmsBaseUrl);
229 AsyncRestClient producer =
230 restClientFactory.createRestClientNoHttpProxy(this.applicationConfig.getDmaapProducerTopicUrl());
231 this.dmaapMessageHandler = new DmaapMessageHandler(producer, pmsClient);
233 return this.dmaapMessageHandler;