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