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.lang.invoke.MethodHandles;
30 import java.time.Duration;
31 import java.util.ArrayList;
32 import java.util.List;
34 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
35 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
36 import org.onap.ccsdk.oran.a1policymanagementservice.clients.SecurityContext;
37 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.springframework.beans.factory.annotation.Autowired;
41 import org.springframework.beans.factory.annotation.Value;
42 import org.springframework.http.HttpStatus;
43 import org.springframework.stereotype.Component;
45 import reactor.core.publisher.Flux;
46 import reactor.core.publisher.FluxSink;
47 import reactor.core.publisher.Mono;
50 * The class fetches incoming requests from DMAAP. It uses the timeout parameter
51 * that lets the MessageRouter keep the connection with the Kafka open until
52 * requests are sent in.
55 * this service will regularly check the configuration and start polling DMaaP
56 * if the configuration is added. If the DMaaP configuration is removed, then
57 * the service will stop polling and resume checking for configuration.
60 * Each received request is processed by {@link DmaapMessageHandler}.
63 public class DmaapMessageConsumer {
65 protected static final Duration TIME_BETWEEN_DMAAP_RETRIES = Duration.ofSeconds(10);
67 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
69 private final ApplicationConfig applicationConfig;
71 private DmaapMessageHandler dmaapMessageHandler = null;
73 private final Gson gson;
75 private final AsyncRestClientFactory restClientFactory;
77 private final InfiniteFlux infiniteSubmitter = new InfiniteFlux();
79 @Value("${server.http-port}")
80 private int localServerHttpPort;
82 private static class InfiniteFlux {
83 private FluxSink<Integer> sink;
84 private int counter = 0;
86 public synchronized Flux<Integer> start() {
88 return Flux.create(this::next).doOnRequest(this::onRequest);
91 public synchronized void stop() {
92 if (this.sink != null) {
98 void onRequest(long no) {
99 for (long i = 0; i < no; ++i) {
100 sink.next(counter++);
104 void next(FluxSink<Integer> sink) {
106 sink.next(counter++);
112 public DmaapMessageConsumer(ApplicationConfig applicationConfig, SecurityContext securityContext) {
113 this.applicationConfig = applicationConfig;
114 GsonBuilder gsonBuilder = new GsonBuilder();
115 this.gson = gsonBuilder.create();
116 this.restClientFactory = new AsyncRestClientFactory(applicationConfig.getWebClientConfig(), securityContext);
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 return delay().flatMap(o -> Mono.empty());
217 logger.debug("fetchFromDmaap");
218 String topicUrl = this.applicationConfig.getDmaapConsumerTopicUrl();
220 return getFromMessageRouter(topicUrl) //
221 .onErrorResume(throwable -> delay().flatMap(o -> Mono.empty()));
224 private DmaapMessageHandler getDmaapMessageHandler() {
225 if (this.dmaapMessageHandler == null) {
226 String pmsBaseUrl = "http://localhost:" + this.localServerHttpPort;
227 AsyncRestClient pmsClient = restClientFactory.createRestClientNoHttpProxy(pmsBaseUrl);
228 AsyncRestClient producer =
229 restClientFactory.createRestClientNoHttpProxy(this.applicationConfig.getDmaapProducerTopicUrl());
230 this.dmaapMessageHandler = new DmaapMessageHandler(producer, pmsClient);
232 return this.dmaapMessageHandler;