fix oauth code
[ccsdk/features.git] / sdnr / wt / mountpoint-registrar / provider / src / main / java / org / onap / ccsdk / features / sdnr / wt / mountpointregistrar / impl / StrimziKafkaVESMsgConsumerImpl.java
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 com.fasterxml.jackson.core.JsonProcessingException;
23 import com.fasterxml.jackson.databind.JsonNode;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import java.util.List;
26 import java.util.Properties;
27 import java.util.concurrent.ExecutionException;
28 import org.apache.kafka.clients.CommonClientConfigs;
29 import org.apache.kafka.clients.admin.Admin;
30 import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.config.GeneralConfig;
31 import org.onap.ccsdk.features.sdnr.wt.mountpointregistrar.kafka.VESMsgKafkaConsumer;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 public abstract class StrimziKafkaVESMsgConsumerImpl
36         implements StrimziKafkaVESMsgConsumer, StrimziKafkaVESMsgValidator {
37
38     private static final Logger LOG = LoggerFactory.getLogger(StrimziKafkaVESMsgConsumerImpl.class);
39     private static final String DEFAULT_SDNRUSER = "admin";
40     private static final String DEFAULT_SDNRPASSWD = "admin";
41
42     private final String name = this.getClass().getSimpleName();
43     private VESMsgKafkaConsumer consumer = null;
44     private boolean running = false;
45     private boolean ready = false;
46     private int fetchPause = 5000; // Default pause between fetch - 5 seconds
47     protected final GeneralConfig generalConfig;
48     Admin kafkaAdminClient = null;
49
50     protected StrimziKafkaVESMsgConsumerImpl(GeneralConfig generalConfig) {
51         this.generalConfig = generalConfig;
52     }
53
54     /*
55      * Thread to fetch messages from the Kafka topic. Waits for the messages to
56      * arrive on the topic until a certain timeout and returns. If no data arrives
57      * on the topic, sleeps for a certain time period before checking again
58      */
59     @Override
60     public void run() {
61         if (ready) {
62             running = true;
63             while (running) {
64                 try {
65                     boolean noData = true;
66                     List<String> consumerResponse = null;
67                     if (isTopicExists(consumer.getTopicName())) {
68                         consumerResponse = consumer.poll();
69                         for (String msg : consumerResponse) {
70                             noData = false;
71                             LOG.debug("{} received ActualMessage from Kafka VES Message topic {}", name, msg);
72                             if (isMessageValid(msg)) {
73                                 processMsg(msg);
74                             }
75                         }
76                     }
77                     if (noData) {
78                         pauseThread();
79                     }
80                 } catch (InterruptedException e) {
81                     LOG.warn("Caught exception reading from Kafka Message Topic", e);
82                     Thread.currentThread().interrupt();
83                 } catch (JsonProcessingException jsonProcessingException) {
84                     LOG.warn("Failed to convert message to JsonNode: {}", jsonProcessingException.getMessage());
85                 } catch (InvalidMessageException invalidMessageException) {
86                     LOG.warn("Message is invalid because of: {}", invalidMessageException.getMessage());
87                 } catch (Exception e) {
88                     LOG.error("Caught exception reading from Kafka Message Topic", e);
89                     running = false;
90                 }
91             }
92         }
93     }
94
95     @Override
96     public boolean isMessageValid(String message) {
97         return true;
98     }
99
100     protected JsonNode convertMessageToJsonNode(String message) throws JsonProcessingException {
101         return new ObjectMapper().readTree(message);
102     }
103
104     /*
105      * Create a Kafka consumer by specifying properties containing information such as
106      * topic name, timeout, URL etc
107      */
108     @Override
109     public void init(Properties strimziKafkaProperties, Properties consumerProperties) {
110         Properties props = new Properties();
111         props.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, strimziKafkaProperties.getProperty("bootstrapServers"));
112         kafkaAdminClient = Admin.create(props);
113
114         try {
115             this.consumer = new VESMsgKafkaConsumer(strimziKafkaProperties, consumerProperties);
116             this.consumer.subscribe(consumerProperties.getProperty("topic"));
117             ready = true;
118         } catch (Exception e) {
119             LOG.error("Error initializing Kafka Message consumer from file {} {}", consumerProperties, e);
120         }
121     }
122
123     private void pauseThread() throws InterruptedException {
124         if (fetchPause > 0) {
125             LOG.debug("No data received from fetch.  Pausing {} ms before retry", fetchPause);
126             Thread.sleep(fetchPause);
127         } else {
128             LOG.debug("No data received from fetch.  No fetch pause specified - retrying immediately");
129         }
130     }
131
132     private boolean isTopicExists(String topicName) {
133         LOG.trace("Checking for existence of topic - {}", topicName);
134         try {
135             for (String kafkaTopic : kafkaAdminClient.listTopics().names().get()) {
136                 if (kafkaTopic.equals(topicName))
137                     return true;
138             }
139         } catch (InterruptedException | ExecutionException e) {
140             LOG.error("Exception in isTopicExists method - ", e);
141         }
142         return false;
143     }
144
145     @Override
146     public boolean isReady() {
147         return ready;
148     }
149
150     @Override
151     public boolean isRunning() {
152         return running;
153     }
154
155     /*
156      * public String getProperty(String name) { return properties.getProperty(name,
157      * ""); }
158      */
159     @Override
160     public void stopConsumer() {
161         running = false;
162     }
163
164     public String getBaseUrl() {
165         return generalConfig.getBaseUrl();
166     }
167
168     public String getSDNRUser() {
169         return generalConfig.getSDNRUser() != null ? generalConfig.getSDNRUser() : DEFAULT_SDNRUSER;
170     }
171
172     public String getSDNRPasswd() {
173         return generalConfig.getSDNRPasswd() != null ? generalConfig.getSDNRPasswd() : DEFAULT_SDNRPASSWD;
174     }
175 }