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.configuration.ApplicationConfig;
39 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.beans.factory.annotation.Value;
44 import org.springframework.http.HttpStatus;
45 import org.springframework.http.ResponseEntity;
46 import org.springframework.stereotype.Component;
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 @Value("${server.http-port}")
75 private int localServerHttpPort;
78 public DmaapMessageConsumer(ApplicationConfig applicationConfig) {
79 this.applicationConfig = applicationConfig;
80 GsonBuilder gsonBuilder = new GsonBuilder();
81 ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
82 gson = gsonBuilder.create();
86 * Starts the consumer. If there is a DMaaP configuration, it will start polling
87 * for messages. Otherwise it will check regularly for the configuration.
89 * @return the running thread, for test purposes.
91 public Thread start() {
92 Thread thread = new Thread(this::messageHandlingLoop);
97 private void messageHandlingLoop() {
98 while (!isStopped()) {
100 if (isDmaapConfigured()) {
101 Iterable<DmaapRequestMessage> dmaapMsgs = fetchAllMessages();
102 if (dmaapMsgs != null && Iterables.size(dmaapMsgs) > 0) {
103 logger.debug("Fetched all the messages from DMAAP and will start to process the messages");
104 for (DmaapRequestMessage msg : dmaapMsgs) {
109 sleep(TIME_BETWEEN_DMAAP_RETRIES); // wait for configuration
111 } catch (Exception e) {
112 logger.warn("{}", e.getMessage());
113 sleep(TIME_BETWEEN_DMAAP_RETRIES);
118 protected boolean isStopped() {
122 protected boolean isDmaapConfigured() {
123 String producerTopicUrl = applicationConfig.getDmaapProducerTopicUrl();
124 String consumerTopicUrl = applicationConfig.getDmaapConsumerTopicUrl();
125 return (producerTopicUrl != null && consumerTopicUrl != null && !producerTopicUrl.isEmpty()
126 && !consumerTopicUrl.isEmpty());
129 private <T> List<T> parseList(String jsonString, Class<T> clazz) {
130 List<T> result = new ArrayList<>();
131 JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
132 for (JsonElement jsonElement : jsonArr) {
133 // The element can either be a JsonObject or a JsonString
134 if (jsonElement.isJsonPrimitive()) {
135 T json = gson.fromJson(jsonElement.getAsString(), clazz);
138 T json = gson.fromJson(jsonElement.toString(), clazz);
145 private void sendErrorResponse(String response) {
146 DmaapRequestMessage fakeRequest = ImmutableDmaapRequestMessage.builder() //
148 .correlationId("") //
149 .operation(DmaapRequestMessage.Operation.PUT) //
151 .payload(Optional.empty()) //
157 getDmaapMessageHandler().sendDmaapResponse(response, fakeRequest, HttpStatus.BAD_REQUEST).block();
160 List<DmaapRequestMessage> parseMessages(String jsonString) throws ServiceException {
162 return parseList(jsonString, DmaapRequestMessage.class);
163 } catch (Exception e) {
164 sendErrorResponse("Not parsable request received, reason:" + e.toString() + ", input :" + jsonString);
165 throw new ServiceException("Could not parse incomming request. Reason :" + e.getMessage());
169 protected Iterable<DmaapRequestMessage> fetchAllMessages() throws ServiceException {
170 String topicUrl = this.applicationConfig.getDmaapConsumerTopicUrl();
171 AsyncRestClient consumer = getMessageRouterConsumer();
172 ResponseEntity<String> response = consumer.getForEntity(topicUrl).block();
173 logger.debug("DMaaP consumer received {} : {}", response.getStatusCode(), response.getBody());
174 if (response.getStatusCode().is2xxSuccessful()) {
175 return parseMessages(response.getBody());
177 throw new ServiceException("Cannot fetch because of Error respons: " + response.getStatusCode().toString()
178 + " " + response.getBody());
182 private void processMsg(DmaapRequestMessage msg) {
183 logger.debug("Message Reveived from DMAAP : {}", msg);
184 getDmaapMessageHandler().handleDmaapMsg(msg);
187 protected DmaapMessageHandler getDmaapMessageHandler() {
188 if (this.dmaapMessageHandler == null) {
189 String pmsBaseUrl = "http://localhost:" + this.localServerHttpPort;
190 AsyncRestClient pmsClient = new AsyncRestClient(pmsBaseUrl, this.applicationConfig.getWebClientConfig());
191 AsyncRestClient producer = new AsyncRestClient(this.applicationConfig.getDmaapProducerTopicUrl(),
192 this.applicationConfig.getWebClientConfig());
193 this.dmaapMessageHandler = new DmaapMessageHandler(producer, pmsClient);
195 return this.dmaapMessageHandler;
198 protected void sleep(Duration duration) {
200 Thread.sleep(duration.toMillis());
201 } catch (Exception e) {
202 logger.error("Failed to put the thread to sleep", e);
206 protected AsyncRestClient getMessageRouterConsumer() {
207 return new AsyncRestClient("", this.applicationConfig.getWebClientConfig());