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