46dd2ee2a3a4cfe330dd14592988fd3963a401c3
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / dmaap / DmaapMessageConsumer.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2020 Nordix Foundation
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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===================================
19  */
20
21 package org.oransc.policyagent.dmaap;
22
23 import com.google.common.collect.Iterables;
24
25 import java.io.IOException;
26 import java.time.Duration;
27 import java.util.Properties;
28
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.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.springframework.beans.factory.annotation.Autowired;
39 import org.springframework.beans.factory.annotation.Value;
40 import org.springframework.stereotype.Component;
41
42 @Component
43 public class DmaapMessageConsumer implements Runnable {
44
45     private static final Logger logger = LoggerFactory.getLogger(DmaapMessageConsumer.class);
46
47     @SuppressWarnings("squid:S00116") // To avoid warning about DMAAP abbreviation.
48     final Duration TIME_BETWEEN_DMAAP_POLLS = Duration.ofSeconds(10);
49
50     private final ApplicationConfig applicationConfig;
51
52     @Value("${server.port}")
53     private int localServerPort;
54
55     @Autowired
56     public DmaapMessageConsumer(ApplicationConfig applicationConfig) {
57         this.applicationConfig = applicationConfig;
58
59         Thread thread = new Thread(this);
60         thread.start();
61     }
62
63     private boolean isDmaapConfigured() {
64         Properties consumerCfg = applicationConfig.getDmaapConsumerConfig();
65         Properties producerCfg = applicationConfig.getDmaapPublisherConfig();
66         return (consumerCfg != null && consumerCfg.size() > 0 && producerCfg != null && producerCfg.size() > 0);
67     }
68
69     @Override
70     public void run() {
71         while (sleep(TIME_BETWEEN_DMAAP_POLLS) && isDmaapConfigured()) {
72             try {
73                 Iterable<String> dmaapMsgs = fetchAllMessages();
74                 if (dmaapMsgs != null && Iterables.size(dmaapMsgs) > 0) {
75                     logger.debug("Fetched all the messages from DMAAP and will start to process the messages");
76                     for (String msg : dmaapMsgs) {
77                         processMsg(msg);
78                     }
79                 }
80             } catch (Exception e) {
81                 logger.warn("{}: cannot fetch because of ", this, e.getMessage(), e);
82                 sleep(TIME_BETWEEN_DMAAP_POLLS);
83             }
84         }
85     }
86
87     private Iterable<String> fetchAllMessages() throws ServiceException, IOException {
88         Properties dmaapConsumerProperties = this.applicationConfig.getDmaapConsumerConfig();
89         MRConsumer consumer = MRClientFactory.createConsumer(dmaapConsumerProperties);
90         MRConsumerResponse response = consumer.fetchWithReturnConsumerResponse();
91         if (response == null || !"200".equals(response.getResponseCode())) {
92             throw new ServiceException("DMaaP NULL response received");
93         } else {
94             logger.debug("DMaaP consumer received {} : {}", response.getResponseCode(), response.getResponseMessage());
95             return response.getActualMessages();
96         }
97     }
98
99     private void processMsg(String msg) throws IOException {
100         logger.debug("Message Reveived from DMAAP : {}", msg);
101         createDmaapMessageHandler().handleDmaapMsg(msg);
102     }
103
104     private DmaapMessageHandler createDmaapMessageHandler() throws IOException {
105         String agentBaseUrl = "http://localhost:" + this.localServerPort;
106         AsyncRestClient agentClient = new AsyncRestClient(agentBaseUrl);
107         Properties dmaapPublisherProperties = applicationConfig.getDmaapPublisherConfig();
108         MRBatchingPublisher producer = MRClientFactory.createBatchingPublisher(dmaapPublisherProperties);
109
110         return new DmaapMessageHandler(producer, agentClient);
111     }
112
113     private boolean sleep(Duration duration) {
114         try {
115             Thread.sleep(duration.toMillis());
116             return true;
117         } catch (Exception e) {
118             logger.error("Failed to put the thread to sleep", e);
119             return false;
120         }
121     }
122 }