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 for (long i = 0; i < no; ++i) {
103 void next(FluxSink<Integer> sink) {
105 sink.next(counter++);
111 public DmaapMessageConsumer(ApplicationConfig applicationConfig, SecurityContext securityContext) {
112 this.applicationConfig = applicationConfig;
113 GsonBuilder gsonBuilder = new GsonBuilder();
114 this.gson = gsonBuilder.create();
115 this.restClientFactory = new AsyncRestClientFactory(applicationConfig.getWebClientConfig(), securityContext);
119 * Starts the DMAAP consumer. If there is a DMaaP configuration, it will start
120 * polling for messages. Otherwise it will check regularly for the
124 public void start() {
125 infiniteSubmitter.stop();
127 createTask().subscribe(//
128 value -> logger.debug("DmaapMessageConsumer next: {}", value), //
129 throwable -> logger.error("DmaapMessageConsumer error: {}", throwable.getMessage()), //
130 () -> logger.warn("DmaapMessageConsumer stopped") //
134 protected Flux<String> createTask() {
135 return infiniteFlux() //
136 .flatMap(notUsed -> fetchFromDmaap(), 1) //
137 .doOnNext(message -> logger.debug("Message Reveived from DMAAP : {}", message)) //
138 .flatMap(this::parseReceivedMessage, 1)//
139 .flatMap(this::handleDmaapMsg, 1) //
140 .onErrorResume(throwable -> Mono.empty());
143 protected Flux<Integer> infiniteFlux() {
144 return infiniteSubmitter.start();
147 protected Mono<Object> delay() {
148 return Mono.delay(TIME_BETWEEN_DMAAP_RETRIES).flatMap(o -> Mono.empty());
151 private <T> List<T> parseList(String jsonString, Class<T> clazz) {
152 List<T> result = new ArrayList<>();
153 JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
154 for (JsonElement jsonElement : jsonArr) {
155 // The element can either be a JsonObject or a JsonString
156 if (jsonElement.isJsonPrimitive()) {
157 T json = gson.fromJson(jsonElement.getAsString(), clazz);
160 T json = gson.fromJson(jsonElement.toString(), clazz);
167 protected boolean isDmaapConfigured() {
168 String producerTopicUrl = applicationConfig.getDmaapProducerTopicUrl();
169 String consumerTopicUrl = applicationConfig.getDmaapConsumerTopicUrl();
170 return (producerTopicUrl != null && consumerTopicUrl != null && !producerTopicUrl.isEmpty()
171 && !consumerTopicUrl.isEmpty());
174 protected Mono<String> handleDmaapMsg(DmaapRequestMessage dmaapRequestMessage) {
175 return getDmaapMessageHandler().handleDmaapMsg(dmaapRequestMessage);
178 protected Mono<String> getFromMessageRouter(String topicUrl) {
179 logger.trace("getFromMessageRouter {}", topicUrl);
180 AsyncRestClient c = restClientFactory.createRestClientNoHttpProxy("");
181 return c.get(topicUrl);
184 protected Flux<DmaapRequestMessage> parseReceivedMessage(String jsonString) {
186 logger.trace("parseMessages {}", jsonString);
187 return Flux.fromIterable(parseList(jsonString, DmaapRequestMessage.class));
188 } catch (Exception e) {
189 logger.error("parseMessages error {}", jsonString);
190 return sendErrorResponse("Could not parse: " + jsonString) //
191 .flatMapMany(s -> Flux.empty());
195 protected Mono<String> sendErrorResponse(String response) {
196 logger.debug("sendErrorResponse {}", response);
197 DmaapRequestMessage fakeRequest = DmaapRequestMessage.builder() //
199 .correlationId("") //
200 .operation(DmaapRequestMessage.Operation.PUT) //
208 return getDmaapMessageHandler().sendDmaapResponse(response, fakeRequest, HttpStatus.BAD_REQUEST) //
209 .onErrorResume(e -> Mono.empty());
212 private Mono<String> fetchFromDmaap() {
213 if (!this.isDmaapConfigured()) {
214 return delay().flatMap(o -> Mono.empty());
216 logger.debug("fetchFromDmaap");
217 String topicUrl = this.applicationConfig.getDmaapConsumerTopicUrl();
219 return getFromMessageRouter(topicUrl) //
220 .onErrorResume(throwable -> delay().flatMap(o -> Mono.empty()));
223 private DmaapMessageHandler getDmaapMessageHandler() {
224 if (this.dmaapMessageHandler == null) {
225 String pmsBaseUrl = "http://localhost:" + this.localServerHttpPort;
226 AsyncRestClient pmsClient = restClientFactory.createRestClientNoHttpProxy(pmsBaseUrl);
227 AsyncRestClient producer =
228 restClientFactory.createRestClientNoHttpProxy(this.applicationConfig.getDmaapProducerTopicUrl());
229 this.dmaapMessageHandler = new DmaapMessageHandler(producer, pmsClient);
231 return this.dmaapMessageHandler;