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