Merge "Add sdnc-a1-controller in build process"
[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 /**
43  * The class fetched incoming requests from DMAAP on regular intervals. Each
44  * received request is proceesed by DmaapMessageHandler.
45  */
46 @Component
47 public class DmaapMessageConsumer implements Runnable {
48
49     private static final Logger logger = LoggerFactory.getLogger(DmaapMessageConsumer.class);
50
51     private static final Duration TIME_BETWEEN_DMAAP_POLLS = Duration.ofSeconds(10);
52
53     private final ApplicationConfig applicationConfig;
54
55     @Value("${server.port}")
56     private int localServerPort;
57
58     @Autowired
59     public DmaapMessageConsumer(ApplicationConfig applicationConfig) {
60         this.applicationConfig = applicationConfig;
61
62         Thread thread = new Thread(this);
63         thread.start();
64     }
65
66     private boolean isDmaapConfigured() {
67         Properties consumerCfg = applicationConfig.getDmaapConsumerConfig();
68         Properties producerCfg = applicationConfig.getDmaapPublisherConfig();
69         return (consumerCfg != null && consumerCfg.size() > 0 && producerCfg != null && producerCfg.size() > 0);
70     }
71
72     @Override
73     public void run() {
74         while (sleep(TIME_BETWEEN_DMAAP_POLLS) && isDmaapConfigured()) {
75             try {
76                 Iterable<String> dmaapMsgs = fetchAllMessages();
77                 if (dmaapMsgs != null && Iterables.size(dmaapMsgs) > 0) {
78                     logger.debug("Fetched all the messages from DMAAP and will start to process the messages");
79                     for (String msg : dmaapMsgs) {
80                         processMsg(msg);
81                     }
82                 }
83             } catch (Exception e) {
84                 logger.warn("{}: cannot fetch because of {}", this, e.getMessage());
85                 sleep(TIME_BETWEEN_DMAAP_POLLS);
86             }
87         }
88     }
89
90     private Iterable<String> fetchAllMessages() throws ServiceException, IOException {
91         Properties dmaapConsumerProperties = this.applicationConfig.getDmaapConsumerConfig();
92         MRConsumer consumer = getMessageRouterConsumer(dmaapConsumerProperties);
93         MRConsumerResponse response = consumer.fetchWithReturnConsumerResponse();
94         if (response == null || !"200".equals(response.getResponseCode())) {
95             String errorMessage = "DMaaP NULL response received";
96             if (response != null) {
97                 errorMessage = "Error respons " + response.getResponseCode() + " " + response.getResponseMessage()
98                     + " from DMaaP.";
99             }
100             throw new ServiceException(errorMessage);
101         } else {
102             logger.debug("DMaaP consumer received {} : {}", response.getResponseCode(), response.getResponseMessage());
103             return response.getActualMessages();
104         }
105     }
106
107     private void processMsg(String msg) throws IOException {
108         logger.debug("Message Reveived from DMAAP : {}", msg);
109         getDmaapMessageHandler().handleDmaapMsg(msg);
110     }
111
112     private DmaapMessageHandler getDmaapMessageHandler() throws IOException {
113         String agentBaseUrl = "http://localhost:" + this.localServerPort;
114         AsyncRestClient agentClient = createRestClient(agentBaseUrl);
115         Properties dmaapPublisherProperties = applicationConfig.getDmaapPublisherConfig();
116         MRBatchingPublisher producer = getMessageRouterPublisher(dmaapPublisherProperties);
117
118         return createDmaapMessageHandler(agentClient, producer);
119     }
120
121     boolean sleep(Duration duration) {
122         try {
123             Thread.sleep(duration.toMillis());
124             return true;
125         } catch (Exception e) {
126             logger.error("Failed to put the thread to sleep", e);
127             return false;
128         }
129     }
130
131     MRConsumer getMessageRouterConsumer(Properties dmaapConsumerProperties) throws IOException {
132         return MRClientFactory.createConsumer(dmaapConsumerProperties);
133     }
134
135     DmaapMessageHandler createDmaapMessageHandler(AsyncRestClient agentClient, MRBatchingPublisher producer) {
136         return new DmaapMessageHandler(producer, agentClient);
137     }
138
139     AsyncRestClient createRestClient(String agentBaseUrl) {
140         return new AsyncRestClient(agentBaseUrl);
141     }
142
143     MRBatchingPublisher getMessageRouterPublisher(Properties dmaapPublisherProperties) throws IOException {
144         return MRClientFactory.createBatchingPublisher(dmaapPublisherProperties);
145     }
146 }