2 * ========================LICENSE_START=================================
5 * Copyright (C) 2020 Nordix Foundation
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.oransc.policyagent.dmaap;
23 import com.google.common.collect.Iterables;
25 import java.io.IOException;
26 import java.time.Duration;
27 import java.util.Properties;
29 import org.onap.dmaap.mr.client.MRBatchingPublisher;
30 import org.onap.dmaap.mr.client.MRClientFactory;
31 import org.onap.dmaap.mr.client.MRConsumer;
32 import org.onap.dmaap.mr.client.response.MRConsumerResponse;
33 import org.oransc.policyagent.clients.AsyncRestClient;
34 import org.oransc.policyagent.configuration.ApplicationConfig;
35 import org.oransc.policyagent.exceptions.ServiceException;
36 import org.oransc.policyagent.tasks.RefreshConfigTask;
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.stereotype.Component;
44 * The class fetches incoming requests from DMAAP. It uses the timeout parameter that lets the MessageRouter keep the
45 * connection with the Kafka open until requests are sent in.
47 * If there is no DMaaP configuration in the application configuration, then this service will regularly check the
48 * configuration and start polling DMaaP if the configuration is added. If the DMaaP configuration is removed, then the
49 * service will stop polling and resume checking for configuration.
51 * Each received request is processed by {@link DmaapMessageHandler}.
54 public class DmaapMessageConsumer {
56 protected static final Duration TIME_BETWEEN_DMAAP_RETRIES = Duration.ofSeconds(10);
58 private static final Logger logger = LoggerFactory.getLogger(DmaapMessageConsumer.class);
60 private final ApplicationConfig applicationConfig;
62 @Value("${server.port}")
63 private int localServerPort;
66 public DmaapMessageConsumer(ApplicationConfig applicationConfig) {
67 this.applicationConfig = applicationConfig;
70 public Thread start() {
71 Thread thread = new Thread(() -> this.checkConfigLoop());
76 private void checkConfigLoop() {
77 while (!isStopped()) {
78 if (isDmaapConfigured()) {
79 messageHandlingLoop();
81 sleep(RefreshConfigTask.CONFIG_REFRESH_INTERVAL);
86 private void messageHandlingLoop() {
87 while (!isStopped() && isDmaapConfigured()) {
89 Iterable<String> dmaapMsgs = fetchAllMessages();
90 if (dmaapMsgs != null && Iterables.size(dmaapMsgs) > 0) {
91 logger.debug("Fetched all the messages from DMAAP and will start to process the messages");
92 for (String msg : dmaapMsgs) {
96 } catch (Exception e) {
97 logger.warn("Cannot fetch because of {}", e.getMessage());
98 sleep(TIME_BETWEEN_DMAAP_RETRIES);
103 protected boolean isStopped() {
107 protected boolean isDmaapConfigured() {
108 Properties consumerCfg = applicationConfig.getDmaapConsumerConfig();
109 Properties producerCfg = applicationConfig.getDmaapPublisherConfig();
110 return (consumerCfg != null && consumerCfg.size() > 0 && producerCfg != null && producerCfg.size() > 0);
113 protected Iterable<String> fetchAllMessages() throws ServiceException, IOException {
114 Properties dmaapConsumerProperties = this.applicationConfig.getDmaapConsumerConfig();
115 MRConsumer consumer = getMessageRouterConsumer(dmaapConsumerProperties);
116 MRConsumerResponse response = consumer.fetchWithReturnConsumerResponse();
117 if (response == null || !"200".equals(response.getResponseCode())) {
118 String errorMessage = "DMaaP NULL response received";
119 if (response != null) {
120 errorMessage = "Error respons " + response.getResponseCode() + " " + response.getResponseMessage()
123 throw new ServiceException(errorMessage);
125 logger.debug("DMaaP consumer received {} : {}", response.getResponseCode(), response.getResponseMessage());
126 return response.getActualMessages();
130 private void processMsg(String msg) throws IOException {
131 logger.debug("Message Reveived from DMAAP : {}", msg);
132 getDmaapMessageHandler().handleDmaapMsg(msg);
135 private DmaapMessageHandler getDmaapMessageHandler() throws IOException {
136 String agentBaseUrl = "https://localhost:" + this.localServerPort;
137 AsyncRestClient agentClient = createRestClient(agentBaseUrl);
138 Properties dmaapPublisherProperties = applicationConfig.getDmaapPublisherConfig();
139 MRBatchingPublisher producer = getMessageRouterPublisher(dmaapPublisherProperties);
141 return createDmaapMessageHandler(agentClient, producer);
144 protected void sleep(Duration duration) {
146 Thread.sleep(duration.toMillis());
147 } catch (Exception e) {
148 logger.error("Failed to put the thread to sleep", e);
152 protected MRConsumer getMessageRouterConsumer(Properties dmaapConsumerProperties) throws IOException {
153 return MRClientFactory.createConsumer(dmaapConsumerProperties);
156 protected DmaapMessageHandler createDmaapMessageHandler(AsyncRestClient agentClient, MRBatchingPublisher producer) {
157 return new DmaapMessageHandler(producer, agentClient);
160 protected AsyncRestClient createRestClient(String agentBaseUrl) {
161 return new AsyncRestClient(agentBaseUrl);
164 protected MRBatchingPublisher getMessageRouterPublisher(Properties dmaapPublisherProperties) throws IOException {
165 return MRClientFactory.createBatchingPublisher(dmaapPublisherProperties);