[SO] Code improvement in bpmn-infra supporting kafka change
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / java / org / onap / so / bpmn / infrastructure / pnf / kafka / PnfEventReadyKafkaClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2018 Nokia.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22 package org.onap.so.bpmn.infrastructure.pnf.kafka;
23
24 import java.io.IOException;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ScheduledThreadPoolExecutor;
30 import java.util.concurrent.TimeUnit;
31 import org.onap.so.client.kafka.KafkaConsumerImpl;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.springframework.beans.factory.annotation.Autowired;
35 import org.springframework.core.env.Environment;
36 import org.springframework.stereotype.Component;
37
38 @Component
39 public class PnfEventReadyKafkaClient implements KafkaClient {
40     private static final Logger logger = LoggerFactory.getLogger(PnfEventReadyKafkaClient.class);
41     private Map<String, Runnable> pnfCorrelationIdToThreadMap;
42     private int topicListenerDelayInSeconds;
43     private volatile ScheduledThreadPoolExecutor executor;
44     private volatile boolean kafkaThreadListenerIsRunning;
45     private KafkaConsumerImpl consumerForPnfReady;
46     private KafkaConsumerImpl consumerForPnfUpdate;
47     private String pnfReadyTopic;
48     private String pnfUpdateTopic;
49     private String consumerGroup;
50     private String consumerId;
51     private String consumerIdUpdate;
52
53
54
55     @Autowired
56     public PnfEventReadyKafkaClient(Environment env) throws IOException {
57         pnfCorrelationIdToThreadMap = new ConcurrentHashMap<>();
58         topicListenerDelayInSeconds = env.getProperty("pnf.kafka.topicListenerDelayInSeconds", Integer.class);
59         executor = null;
60         try {
61             consumerForPnfReady = new KafkaConsumerImpl(env.getProperty("pnf.kafka.kafkaBootstrapServers"));
62             consumerForPnfUpdate = new KafkaConsumerImpl(env.getProperty("pnf.kafka.kafkaBootstrapServers"));
63         } catch (Exception e) {
64             throw new RuntimeException(e);
65         }
66         pnfReadyTopic = env.getProperty("pnf.kafka.pnfReadyTopicName");
67         pnfUpdateTopic = env.getProperty("pnf.kafka.pnfUpdateTopicName");
68         consumerGroup = env.getProperty("pnf.kafka.consumerGroup");
69         consumerId = env.getProperty("pnf.kafka.consumerId");
70         consumerIdUpdate = env.getProperty("pnf.kafka.consumerIdUpdate");
71     }
72
73
74     @Override
75     public synchronized void registerForUpdate(String pnfCorrelationId, Runnable informConsumer) {
76         logger.debug("registering for pnf ready kafka event for pnf correlation id: {}", pnfCorrelationId);
77         pnfCorrelationIdToThreadMap.put(pnfCorrelationId, informConsumer);
78         if (!kafkaThreadListenerIsRunning) {
79             startKafkaThreadListener();
80         }
81     }
82
83     @Override
84     public synchronized Runnable unregister(String pnfCorrelationId) {
85         logger.debug("unregistering from pnf ready kafka event for pnf correlation id: {}", pnfCorrelationId);
86         Runnable runnable = pnfCorrelationIdToThreadMap.remove(pnfCorrelationId);
87         if (pnfCorrelationIdToThreadMap.isEmpty()) {
88             consumerForPnfUpdate.close();
89             consumerForPnfReady.close();
90             stopKafkaThreadListener();
91         }
92         return runnable;
93     }
94
95     private synchronized void startKafkaThreadListener() {
96         if (!kafkaThreadListenerIsRunning) {
97             executor = new ScheduledThreadPoolExecutor(1);
98             executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
99             executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
100             executor.scheduleWithFixedDelay(new KafkaTopicListenerThread(), 0, topicListenerDelayInSeconds,
101                     TimeUnit.SECONDS);
102             kafkaThreadListenerIsRunning = true;
103         }
104     }
105
106     private synchronized void stopKafkaThreadListener() {
107         if (kafkaThreadListenerIsRunning) {
108             executor.shutdown();
109             kafkaThreadListenerIsRunning = false;
110             executor = null;
111         }
112     }
113
114     class KafkaTopicListenerThread implements Runnable {
115         @Override
116         public void run() {
117             try {
118                 List<String> response;
119                 System.out.println(pnfUpdateTopic + "   " + consumerGroup);
120                 response = consumerForPnfUpdate.get(pnfUpdateTopic, consumerGroup, consumerIdUpdate);
121                 if (response.isEmpty()) {
122                     response = consumerForPnfReady.get(pnfReadyTopic, consumerGroup, consumerId);
123                     getPnfCorrelationIdListFromResponse(response)
124                             .forEach(this::informAboutPnfReadyIfPnfCorrelationIdFound);
125                 } else {
126                     getPnfCorrelationIdListFromResponse(response)
127                             .forEach(this::informAboutPnfReadyIfPnfCorrelationIdFound);
128                 }
129             } catch (IOException e) {
130                 logger.error("Exception caught during sending rest request to kafka for listening event topic", e);
131             }
132         }
133
134         private List<String> getPnfCorrelationIdListFromResponse(List<String> response) throws IOException {
135             if (response != null) {
136                 return JsonUtilForPnfCorrelationId.parseJsonToGelAllPnfCorrelationId(response);
137             }
138             return Collections.emptyList();
139         }
140
141         private void informAboutPnfReadyIfPnfCorrelationIdFound(String pnfCorrelationId) {
142             Runnable runnable = unregister(pnfCorrelationId);
143             if (runnable != null) {
144                 logger.debug("kafka listener gets pnf ready event for pnfCorrelationId: {}", pnfCorrelationId);
145                 runnable.run();
146             }
147         }
148     }
149 }
150