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.common.collect.Iterables;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import com.google.gson.JsonArray;
27 import com.google.gson.JsonElement;
28 import com.google.gson.JsonParser;
29 import com.google.gson.TypeAdapterFactory;
31 import java.time.Duration;
32 import java.util.ArrayList;
33 import java.util.List;
34 import java.util.Optional;
35 import java.util.ServiceLoader;
37 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
38 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
39 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
40 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.beans.factory.annotation.Value;
45 import org.springframework.http.HttpStatus;
46 import org.springframework.http.ResponseEntity;
47 import org.springframework.stereotype.Component;
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(DmaapMessageConsumer.class);
69 private final ApplicationConfig applicationConfig;
71 private DmaapMessageHandler dmaapMessageHandler = null;
73 private final Gson gson;
75 private final AsyncRestClientFactory restClientFactory;
77 @Value("${server.http-port}")
78 private int localServerHttpPort;
81 public DmaapMessageConsumer(ApplicationConfig applicationConfig) {
82 this.applicationConfig = applicationConfig;
83 GsonBuilder gsonBuilder = new GsonBuilder();
84 ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
85 gson = gsonBuilder.create();
86 this.restClientFactory = new AsyncRestClientFactory(applicationConfig.getWebClientConfig());
90 * Starts the consumer. If there is a DMaaP configuration, it will start polling
91 * for messages. Otherwise it will check regularly for the configuration.
93 * @return the running thread, for test purposes.
95 public Thread start() {
96 Thread thread = new Thread(this::messageHandlingLoop);
101 private void messageHandlingLoop() {
102 while (!isStopped()) {
104 if (isDmaapConfigured()) {
105 Iterable<DmaapRequestMessage> dmaapMsgs = fetchAllMessages();
106 if (dmaapMsgs != null && Iterables.size(dmaapMsgs) > 0) {
107 logger.debug("Fetched all the messages from DMAAP and will start to process the messages");
108 for (DmaapRequestMessage msg : dmaapMsgs) {
113 sleep(TIME_BETWEEN_DMAAP_RETRIES); // wait for configuration
115 } catch (Exception e) {
116 logger.warn("{}", e.getMessage());
117 sleep(TIME_BETWEEN_DMAAP_RETRIES);
122 protected boolean isStopped() {
126 protected boolean isDmaapConfigured() {
127 String producerTopicUrl = applicationConfig.getDmaapProducerTopicUrl();
128 String consumerTopicUrl = applicationConfig.getDmaapConsumerTopicUrl();
129 return (producerTopicUrl != null && consumerTopicUrl != null && !producerTopicUrl.isEmpty()
130 && !consumerTopicUrl.isEmpty());
133 private <T> List<T> parseList(String jsonString, Class<T> clazz) {
134 List<T> result = new ArrayList<>();
135 JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
136 for (JsonElement jsonElement : jsonArr) {
137 // The element can either be a JsonObject or a JsonString
138 if (jsonElement.isJsonPrimitive()) {
139 T json = gson.fromJson(jsonElement.getAsString(), clazz);
142 T json = gson.fromJson(jsonElement.toString(), clazz);
149 private void sendErrorResponse(String response) {
150 DmaapRequestMessage fakeRequest = ImmutableDmaapRequestMessage.builder() //
152 .correlationId("") //
153 .operation(DmaapRequestMessage.Operation.PUT) //
155 .payload(Optional.empty()) //
161 getDmaapMessageHandler().sendDmaapResponse(response, fakeRequest, HttpStatus.BAD_REQUEST).block();
164 List<DmaapRequestMessage> parseMessages(String jsonString) throws ServiceException {
166 return parseList(jsonString, DmaapRequestMessage.class);
167 } catch (Exception e) {
168 sendErrorResponse("Not parsable request received, reason:" + e.toString() + ", input :" + jsonString);
169 throw new ServiceException("Could not parse incomming request. Reason :" + e.getMessage());
173 protected Iterable<DmaapRequestMessage> fetchAllMessages() throws ServiceException {
174 String topicUrl = this.applicationConfig.getDmaapConsumerTopicUrl();
175 AsyncRestClient consumer = getMessageRouterConsumer();
176 ResponseEntity<String> response = consumer.getForEntity(topicUrl).block();
177 logger.debug("DMaaP consumer received {} : {}", response.getStatusCode(), response.getBody());
178 if (response.getStatusCode().is2xxSuccessful()) {
179 return parseMessages(response.getBody());
181 throw new ServiceException("Cannot fetch because of Error respons: " + response.getStatusCode().toString()
182 + " " + response.getBody());
186 private void processMsg(DmaapRequestMessage msg) {
187 logger.debug("Message Reveived from DMAAP : {}", msg);
188 getDmaapMessageHandler().handleDmaapMsg(msg);
191 protected DmaapMessageHandler getDmaapMessageHandler() {
192 if (this.dmaapMessageHandler == null) {
193 String pmsBaseUrl = "http://localhost:" + this.localServerHttpPort;
194 AsyncRestClient pmsClient = restClientFactory.createRestClient(pmsBaseUrl);
195 AsyncRestClient producer =
196 restClientFactory.createRestClient(this.applicationConfig.getDmaapProducerTopicUrl());
197 this.dmaapMessageHandler = new DmaapMessageHandler(producer, pmsClient);
199 return this.dmaapMessageHandler;
202 protected void sleep(Duration duration) {
204 Thread.sleep(duration.toMillis());
205 } catch (Exception e) {
206 logger.error("Failed to put the thread to sleep", e);
210 protected AsyncRestClient getMessageRouterConsumer() {
211 return restClientFactory.createRestClient("");