f6e70c6b5ccd0a43d9518f8140db97cf527821fe
[ccsdk/features.git] /
1 /*
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt mountpoint-registrar
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * Copyright (C) 2021 Samsung Electronics Intellectual Property. All rights reserved.
7  * =================================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. 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 distributed under the License
14  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
15  * or implied. See the License for the specific language governing permissions and limitations under
16  * the License.
17  * ============LICENSE_END==========================================================================
18  */
19
20 package org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.impl;
21
22 import java.util.Properties;
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import org.onap.dmaap.mr.client.MRClientFactory;
25 import org.onap.dmaap.mr.client.MRConsumer;
26 import org.onap.dmaap.mr.client.response.MRConsumerResponse;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 public abstract class DMaaPVESMsgConsumerImpl implements DMaaPVESMsgConsumer, DMaaPVESMsgValidator {
31
32     private static final Logger LOG = LoggerFactory.getLogger(DMaaPVESMsgConsumerImpl.class);
33     private static final String DEFAULT_SDNRUSER = "admin";
34     private static final String DEFAULT_SDNRPASSWD = "admin";
35
36     private final String name = this.getClass().getSimpleName();
37     private Properties properties = null;
38     private MRConsumer consumer = null;
39     private boolean running = false;
40     private boolean ready = false;
41     private int fetchPause = 5000; // Default pause between fetch - 5 seconds
42     private int timeout = 15000; // Default timeout - 15 seconds
43     protected final GeneralConfig generalConfig;
44
45     protected DMaaPVESMsgConsumerImpl(GeneralConfig generalConfig) {
46         this.generalConfig = generalConfig;
47     }
48
49     /*
50      * Thread to fetch messages from the DMaaP topic. Waits for the messages to arrive on the topic until a certain timeout and returns.
51      * If no data arrives on the topic, sleeps for a certain time period before checking again
52      */
53     @Override
54     public void run() {
55
56         if (ready) {
57             running = true;
58             while (running) {
59                 try {
60                     boolean noData = true;
61                     MRConsumerResponse consumerResponse = null;
62                     consumerResponse = consumer.fetchWithReturnConsumerResponse(timeout, -1);
63                     for (String msg : consumerResponse.getActualMessages()) {
64                         noData = false;
65                         LOG.debug("{} received ActualMessage from DMaaP VES Message topic {}", name,msg);
66                         if(isMessageValid(msg)) {
67                             processMsg(msg);
68                         }
69                     }
70
71                     if (noData) {
72                         LOG.debug("{} received ResponseCode: {}", name, consumerResponse.getResponseCode());
73                         LOG.debug("{} received ResponseMessage: {}", name, consumerResponse.getResponseMessage());
74                         if ((consumerResponse.getResponseCode() == null)
75                                 && (consumerResponse.getResponseMessage().contains("SocketTimeoutException"))) {
76                             LOG.warn("Client timeout while waiting for response from Server {}",
77                                     consumerResponse.getResponseMessage());
78                         }
79                         pauseThread();
80                     }
81                 } catch (JsonProcessingException jsonProcessingException) {
82                     LOG.warn("Failed to convert message to JsonNode: {}", jsonProcessingException.getMessage());
83                 } catch (InvalidMessageException invalidMessageException) {
84                     LOG.warn("Message is invalid because of: {}", invalidMessageException.getMessage());
85                 } catch (Exception e) {
86                     LOG.error("Caught exception reading from DMaaP VES Message Topic", e);
87                     running = false;
88                 }
89             }
90         }
91     }
92
93     @Override
94     public boolean isMessageValid(String message) {
95         return true;
96     }
97
98     /*
99      * Create a consumer by specifying  properties containing information such as topic name, timeout, URL etc
100      */
101     @Override
102     public void init(Properties properties) {
103
104         try {
105
106             String timeoutStr = properties.getProperty("timeout");
107             LOG.debug("timeoutStr: {}", timeoutStr);
108
109             if ((timeoutStr != null) && (timeoutStr.length() > 0)) {
110                 timeout = parseTimeOutValue(timeoutStr);
111             }
112
113             String fetchPauseStr = properties.getProperty("fetchPause");
114             LOG.debug("fetchPause(Str): {}",fetchPauseStr);
115             if ((fetchPauseStr != null) && (fetchPauseStr.length() > 0)) {
116                 fetchPause = parseFetchPause(fetchPauseStr);
117             }
118             LOG.debug("fetchPause: {} ",fetchPause);
119
120             this.consumer = MRClientFactory.createConsumer(properties);
121             ready = true;
122         } catch (Exception e) {
123             LOG.error("Error initializing DMaaP VES Message consumer from file {} {}",properties, e);
124         }
125     }
126
127     private int parseTimeOutValue(String timeoutStr) {
128         try {
129             return Integer.parseInt(timeoutStr);
130         } catch (NumberFormatException e) {
131             LOG.error("Non-numeric value specified for timeout ({})",timeoutStr);
132         }
133         return timeout;
134     }
135
136     private int parseFetchPause(String fetchPauseStr) {
137         try {
138             return Integer.parseInt(fetchPauseStr);
139         } catch (NumberFormatException e) {
140             LOG.error("Non-numeric value specified for fetchPause ({})",fetchPauseStr);
141         }
142         return fetchPause;
143     }
144
145     private void pauseThread() throws InterruptedException {
146         if (fetchPause > 0) {
147             LOG.debug("No data received from fetch.  Pausing {} ms before retry", fetchPause);
148             Thread.sleep(fetchPause);
149         } else {
150             LOG.debug("No data received from fetch.  No fetch pause specified - retrying immediately");
151         }
152     }
153
154     @Override
155     public boolean isReady() {
156         return ready;
157     }
158
159     @Override
160     public boolean isRunning() {
161         return running;
162     }
163
164     public String getProperty(String name) {
165         return properties.getProperty(name, "");
166     }
167
168     @Override
169     public void stopConsumer() {
170         running = false;
171     }
172
173
174     public String getBaseUrl() {
175         return generalConfig.getBaseUrl();
176     }
177
178     public String getSDNRUser() {
179         return generalConfig.getSDNRUser() != null ? generalConfig.getSDNRUser() : DEFAULT_SDNRUSER;
180     }
181
182     public String getSDNRPasswd() {
183         return generalConfig.getSDNRPasswd() != null ? generalConfig.getSDNRPasswd() : DEFAULT_SDNRPASSWD;
184     }
185 }