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;
28 import com.google.gson.TypeAdapterFactory;
30 import java.time.Duration;
31 import java.util.ArrayList;
32 import java.util.List;
33 import java.util.Optional;
34 import java.util.ServiceLoader;
36 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
37 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
38 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.springframework.beans.factory.annotation.Autowired;
42 import org.springframework.beans.factory.annotation.Value;
43 import org.springframework.http.HttpStatus;
44 import org.springframework.stereotype.Component;
46 import reactor.core.publisher.Flux;
47 import reactor.core.publisher.FluxSink;
48 import reactor.core.publisher.Mono;
51 * The class fetches incoming requests from DMAAP. It uses the timeout parameter
52 * that lets the MessageRouter keep the connection with the Kafka open until
53 * requests are sent in.
56 * this service will regularly check the configuration and start polling DMaaP
57 * if the configuration is added. If the DMaaP configuration is removed, then
58 * the service will stop polling and resume checking for configuration.
61 * Each received request is processed by {@link DmaapMessageHandler}.
64 public class DmaapMessageConsumer {
66 protected static final Duration TIME_BETWEEN_DMAAP_RETRIES = Duration.ofSeconds(10);
68 private static final Logger logger = LoggerFactory.getLogger(DmaapMessageConsumer.class);
70 private final ApplicationConfig applicationConfig;
72 private DmaapMessageHandler dmaapMessageHandler = null;
74 private final Gson gson;
76 private final AsyncRestClientFactory restClientFactory;
78 private final InfiniteFlux infiniteSubmitter = new InfiniteFlux();
80 @Value("${server.http-port}")
81 private int localServerHttpPort;
83 private static class InfiniteFlux {
84 private FluxSink<Integer> sink;
85 private int counter = 0;
87 public synchronized Flux<Integer> start() {
89 return Flux.create(this::next).doOnRequest(this::onRequest);
92 public synchronized void stop() {
93 if (this.sink != null) {
99 void onRequest(long no) {
100 logger.debug("InfiniteFlux.onRequest {}", no);
101 for (long i = 0; i < no; ++i) {
102 sink.next(counter++);
106 void next(FluxSink<Integer> sink) {
107 logger.debug("InfiniteFlux.next");
109 sink.next(counter++);
115 public DmaapMessageConsumer(ApplicationConfig applicationConfig) {
116 this.applicationConfig = applicationConfig;
117 GsonBuilder gsonBuilder = new GsonBuilder();
118 ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
119 this.gson = gsonBuilder.create();
120 this.restClientFactory = new AsyncRestClientFactory(applicationConfig.getWebClientConfig());
124 * Starts the DMAAP consumer. If there is a DMaaP configuration, it will start
125 * polling for messages. Otherwise it will check regularly for the
129 public void start() {
130 infiniteSubmitter.stop();
132 createTask().subscribe(//
133 value -> logger.debug("DmaapMessageConsumer next: {}", value), //
134 throwable -> logger.error("DmaapMessageConsumer error: {}", throwable), //
135 () -> logger.warn("DmaapMessageConsumer stopped") //
139 protected Flux<String> createTask() {
140 return infiniteFlux() //
141 .flatMap(notUsed -> fetchFromDmaap(), 1) //
142 .doOnNext(message -> logger.debug("Message Reveived from DMAAP : {}", message)) //
143 .flatMap(this::parseReceivedMessage, 1)//
144 .flatMap(this::handleDmaapMsg, 1) //
145 .onErrorResume(throwable -> Mono.empty());
148 protected Flux<Integer> infiniteFlux() {
149 return infiniteSubmitter.start();
152 protected Mono<Object> delay() {
153 return Mono.delay(TIME_BETWEEN_DMAAP_RETRIES).flatMap(o -> Mono.empty());
156 private <T> List<T> parseList(String jsonString, Class<T> clazz) {
157 List<T> result = new ArrayList<>();
158 JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
159 for (JsonElement jsonElement : jsonArr) {
160 // The element can either be a JsonObject or a JsonString
161 if (jsonElement.isJsonPrimitive()) {
162 T json = gson.fromJson(jsonElement.getAsString(), clazz);
165 T json = gson.fromJson(jsonElement.toString(), clazz);
172 protected boolean isDmaapConfigured() {
173 String producerTopicUrl = applicationConfig.getDmaapProducerTopicUrl();
174 String consumerTopicUrl = applicationConfig.getDmaapConsumerTopicUrl();
175 return (producerTopicUrl != null && consumerTopicUrl != null && !producerTopicUrl.isEmpty()
176 && !consumerTopicUrl.isEmpty());
179 protected Mono<String> handleDmaapMsg(DmaapRequestMessage dmaapRequestMessage) {
180 return getDmaapMessageHandler().handleDmaapMsg(dmaapRequestMessage);
183 protected Mono<String> getFromMessageRouter(String topicUrl) {
184 logger.trace("getFromMessageRouter {}", topicUrl);
185 AsyncRestClient c = restClientFactory.createRestClient("");
186 return c.get(topicUrl);
189 protected Flux<DmaapRequestMessage> parseReceivedMessage(String jsonString) {
191 logger.trace("parseMessages {}", jsonString);
192 return Flux.fromIterable(parseList(jsonString, DmaapRequestMessage.class));
193 } catch (Exception e) {
194 logger.error("parseMessages error {}", jsonString);
195 return sendErrorResponse("Could not parse: " + jsonString) //
196 .flatMapMany(s -> Flux.empty());
200 protected Mono<String> sendErrorResponse(String response) {
201 logger.debug("sendErrorResponse {}", response);
202 DmaapRequestMessage fakeRequest = ImmutableDmaapRequestMessage.builder() //
204 .correlationId("") //
205 .operation(DmaapRequestMessage.Operation.PUT) //
207 .payload(Optional.empty()) //
213 return getDmaapMessageHandler().sendDmaapResponse(response, fakeRequest, HttpStatus.BAD_REQUEST) //
214 .onErrorResume(e -> Mono.empty());
217 private Mono<String> fetchFromDmaap() {
218 if (!this.isDmaapConfigured()) {
219 logger.debug("fetchFromDmaap, no action DMAAP not configured");
220 return delay().flatMap(o -> Mono.empty());
222 logger.debug("fetchFromDmaap");
223 String topicUrl = this.applicationConfig.getDmaapConsumerTopicUrl();
225 return getFromMessageRouter(topicUrl) //
226 .onErrorResume(throwable -> delay().flatMap(o -> Mono.empty()));
229 private DmaapMessageHandler getDmaapMessageHandler() {
230 if (this.dmaapMessageHandler == null) {
231 String pmsBaseUrl = "http://localhost:" + this.localServerHttpPort;
232 AsyncRestClient pmsClient = restClientFactory.createRestClient(pmsBaseUrl);
233 AsyncRestClient producer =
234 restClientFactory.createRestClient(this.applicationConfig.getDmaapProducerTopicUrl());
235 this.dmaapMessageHandler = new DmaapMessageHandler(producer, pmsClient);
237 return this.dmaapMessageHandler;