Merge "Remove unused exceptions from dashboard backend"
[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     final Duration TIME_BETWEEN_DMAAP_POLLS = Duration.ofSeconds(10);
48     private final ApplicationConfig applicationConfig;
49
50     @Value("${server.port}")
51     private int localServerPort;
52
53     @Autowired
54     public DmaapMessageConsumer(ApplicationConfig applicationConfig) {
55         this.applicationConfig = applicationConfig;
56
57         Thread thread = new Thread(this);
58         thread.start();
59     }
60
61     private boolean isDmaapConfigured() {
62         Properties consumerCfg = applicationConfig.getDmaapConsumerConfig();
63         Properties producerCfg = applicationConfig.getDmaapPublisherConfig();
64         return (consumerCfg != null && consumerCfg.size() > 0 && producerCfg != null && producerCfg.size() > 0);
65     }
66
67     @Override
68     public void run() {
69         while (sleep(TIME_BETWEEN_DMAAP_POLLS) && isDmaapConfigured()) {
70             try {
71                 Iterable<String> dmaapMsgs = fetchAllMessages();
72                 if (dmaapMsgs != null && Iterables.size(dmaapMsgs) > 0) {
73                     logger.debug("Fetched all the messages from DMAAP and will start to process the messages");
74                     for (String msg : dmaapMsgs) {
75                         processMsg(msg);
76                     }
77                 }
78             } catch (Exception e) {
79                 logger.warn("{}: cannot fetch because of ", this, e.getMessage(), e);
80                 sleep(TIME_BETWEEN_DMAAP_POLLS);
81             }
82         }
83     }
84
85     private Iterable<String> fetchAllMessages() throws ServiceException, IOException {
86         Properties dmaapConsumerProperties = this.applicationConfig.getDmaapConsumerConfig();
87         MRConsumer consumer = MRClientFactory.createConsumer(dmaapConsumerProperties);
88         MRConsumerResponse response = consumer.fetchWithReturnConsumerResponse();
89         if (response == null || !"200".equals(response.getResponseCode())) {
90             throw new ServiceException("DMaaP NULL response received");
91         } else {
92             logger.debug("DMaaP consumer received {} : {}", response.getResponseCode(), response.getResponseMessage());
93             return response.getActualMessages();
94         }
95     }
96
97     private void processMsg(String msg) throws IOException {
98         logger.debug("Message Reveived from DMAAP : {}", msg);
99         createDmaapMessageHandler().handleDmaapMsg(msg);
100     }
101
102     private DmaapMessageHandler createDmaapMessageHandler() throws IOException {
103         String agentBaseUrl = "http://localhost:" + this.localServerPort;
104         AsyncRestClient agentClient = new AsyncRestClient(agentBaseUrl);
105         Properties dmaapPublisherProperties = applicationConfig.getDmaapPublisherConfig();
106         MRBatchingPublisher producer = MRClientFactory.createBatchingPublisher(dmaapPublisherProperties);
107
108         return new DmaapMessageHandler(producer, agentClient);
109     }
110
111     private boolean sleep(Duration duration) {
112         try {
113             Thread.sleep(duration.toMillis());
114             return true;
115         } catch (Exception e) {
116             logger.error("Failed to put the thread to sleep", e);
117             return false;
118         }
119     }
120 }