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.clients.SecurityContext;
36 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.springframework.beans.factory.annotation.Autowired;
40 import org.springframework.beans.factory.annotation.Value;
41 import org.springframework.http.HttpStatus;
42 import org.springframework.stereotype.Component;
44 import reactor.core.publisher.Flux;
45 import reactor.core.publisher.FluxSink;
46 import reactor.core.publisher.Mono;
49 * The class fetches incoming requests from DMAAP. It uses the timeout parameter
50 * that lets the MessageRouter keep the connection with the Kafka open until
51 * requests are sent in.
54 * this service will regularly check the configuration and start polling DMaaP
55 * if the configuration is added. If the DMaaP configuration is removed, then
56 * the service will stop polling and resume checking for configuration.
59 * Each received request is processed by {@link DmaapMessageHandler}.
62 public class DmaapMessageConsumer {
64 protected static final Duration TIME_BETWEEN_DMAAP_RETRIES = Duration.ofSeconds(10);
66 private static final Logger logger = LoggerFactory.getLogger(DmaapMessageConsumer.class);
68 private final ApplicationConfig applicationConfig;
70 private DmaapMessageHandler dmaapMessageHandler = null;
72 private final Gson gson;
74 private final AsyncRestClientFactory restClientFactory;
76 private final InfiniteFlux infiniteSubmitter = new InfiniteFlux();
78 @Value("${server.http-port}")
79 private int localServerHttpPort;
81 private static class InfiniteFlux {
82 private FluxSink<Integer> sink;
83 private int counter = 0;
85 public synchronized Flux<Integer> start() {
87 return Flux.create(this::next).doOnRequest(this::onRequest);
90 public synchronized void stop() {
91 if (this.sink != null) {
97 void onRequest(long no) {
98 logger.debug("InfiniteFlux.onRequest {}", no);
99 for (long i = 0; i < no; ++i) {
100 sink.next(counter++);
104 void next(FluxSink<Integer> sink) {
105 logger.debug("InfiniteFlux.next");
107 sink.next(counter++);
113 public DmaapMessageConsumer(ApplicationConfig applicationConfig, SecurityContext securityContext) {
114 this.applicationConfig = applicationConfig;
115 GsonBuilder gsonBuilder = new GsonBuilder();
116 this.gson = gsonBuilder.create();
117 this.restClientFactory = new AsyncRestClientFactory(applicationConfig.getWebClientConfig(), securityContext);
121 * Starts the DMAAP consumer. If there is a DMaaP configuration, it will start
122 * polling for messages. Otherwise it will check regularly for the
126 public void start() {
127 infiniteSubmitter.stop();
129 createTask().subscribe(//
130 value -> logger.debug("DmaapMessageConsumer next: {}", value), //
131 throwable -> logger.error("DmaapMessageConsumer error: {}", throwable.getMessage()), //
132 () -> logger.warn("DmaapMessageConsumer stopped") //
136 protected Flux<String> createTask() {
137 return infiniteFlux() //
138 .flatMap(notUsed -> fetchFromDmaap(), 1) //
139 .doOnNext(message -> logger.debug("Message Reveived from DMAAP : {}", message)) //
140 .flatMap(this::parseReceivedMessage, 1)//
141 .flatMap(this::handleDmaapMsg, 1) //
142 .onErrorResume(throwable -> Mono.empty());
145 protected Flux<Integer> infiniteFlux() {
146 return infiniteSubmitter.start();
149 protected Mono<Object> delay() {
150 return Mono.delay(TIME_BETWEEN_DMAAP_RETRIES).flatMap(o -> Mono.empty());
153 private <T> List<T> parseList(String jsonString, Class<T> clazz) {
154 List<T> result = new ArrayList<>();
155 JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
156 for (JsonElement jsonElement : jsonArr) {
157 // The element can either be a JsonObject or a JsonString
158 if (jsonElement.isJsonPrimitive()) {
159 T json = gson.fromJson(jsonElement.getAsString(), clazz);
162 T json = gson.fromJson(jsonElement.toString(), clazz);
169 protected boolean isDmaapConfigured() {
170 String producerTopicUrl = applicationConfig.getDmaapProducerTopicUrl();
171 String consumerTopicUrl = applicationConfig.getDmaapConsumerTopicUrl();
172 return (producerTopicUrl != null && consumerTopicUrl != null && !producerTopicUrl.isEmpty()
173 && !consumerTopicUrl.isEmpty());
176 protected Mono<String> handleDmaapMsg(DmaapRequestMessage dmaapRequestMessage) {
177 return getDmaapMessageHandler().handleDmaapMsg(dmaapRequestMessage);
180 protected Mono<String> getFromMessageRouter(String topicUrl) {
181 logger.trace("getFromMessageRouter {}", topicUrl);
182 AsyncRestClient c = restClientFactory.createRestClientNoHttpProxy("");
183 return c.get(topicUrl);
186 protected Flux<DmaapRequestMessage> parseReceivedMessage(String jsonString) {
188 logger.trace("parseMessages {}", jsonString);
189 return Flux.fromIterable(parseList(jsonString, DmaapRequestMessage.class));
190 } catch (Exception e) {
191 logger.error("parseMessages error {}", jsonString);
192 return sendErrorResponse("Could not parse: " + jsonString) //
193 .flatMapMany(s -> Flux.empty());
197 protected Mono<String> sendErrorResponse(String response) {
198 logger.debug("sendErrorResponse {}", response);
199 DmaapRequestMessage fakeRequest = DmaapRequestMessage.builder() //
201 .correlationId("") //
202 .operation(DmaapRequestMessage.Operation.PUT) //
210 return getDmaapMessageHandler().sendDmaapResponse(response, fakeRequest, HttpStatus.BAD_REQUEST) //
211 .onErrorResume(e -> Mono.empty());
214 private Mono<String> fetchFromDmaap() {
215 if (!this.isDmaapConfigured()) {
216 logger.debug("fetchFromDmaap, no action DMAAP not configured");
217 return delay().flatMap(o -> Mono.empty());
219 logger.debug("fetchFromDmaap");
220 String topicUrl = this.applicationConfig.getDmaapConsumerTopicUrl();
222 return getFromMessageRouter(topicUrl) //
223 .onErrorResume(throwable -> delay().flatMap(o -> Mono.empty()));
226 private DmaapMessageHandler getDmaapMessageHandler() {
227 if (this.dmaapMessageHandler == null) {
228 String pmsBaseUrl = "http://localhost:" + this.localServerHttpPort;
229 AsyncRestClient pmsClient = restClientFactory.createRestClientNoHttpProxy(pmsBaseUrl);
230 AsyncRestClient producer =
231 restClientFactory.createRestClientNoHttpProxy(this.applicationConfig.getDmaapProducerTopicUrl());
232 this.dmaapMessageHandler = new DmaapMessageHandler(producer, pmsClient);
234 return this.dmaapMessageHandler;