CorrelationId cleanup
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / java / org / onap / so / bpmn / infrastructure / pnf / dmaap / PnfEventReadyDmaapClient.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
23 package org.onap.so.bpmn.infrastructure.pnf.dmaap;
24
25 import java.io.IOException;
26 import java.util.Collections;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ScheduledThreadPoolExecutor;
31 import java.util.concurrent.TimeUnit;
32 import javax.ws.rs.core.UriBuilder;
33 import org.apache.http.HttpResponse;
34 import org.apache.http.client.HttpClient;
35 import org.apache.http.client.methods.HttpGet;
36 import org.apache.http.impl.client.HttpClientBuilder;
37 import org.apache.http.util.EntityUtils;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.springframework.beans.factory.annotation.Autowired;
41 import org.springframework.core.env.Environment;
42 import org.springframework.stereotype.Component;
43
44 @Component
45 public class PnfEventReadyDmaapClient implements DmaapClient {
46
47     private static final Logger logger = LoggerFactory.getLogger(PnfEventReadyDmaapClient.class);
48
49     private HttpClient httpClient;
50     private Map<String, Runnable> pnfCorrelationIdToThreadMap;
51     private HttpGet getRequest;
52     private int topicListenerDelayInSeconds;
53     private volatile ScheduledThreadPoolExecutor executor;
54     private volatile boolean dmaapThreadListenerIsRunning;
55
56     @Autowired
57     public PnfEventReadyDmaapClient(Environment env) {
58         httpClient = HttpClientBuilder.create().build();
59         pnfCorrelationIdToThreadMap = new ConcurrentHashMap<>();
60         topicListenerDelayInSeconds = env.getProperty("pnf.dmaap.topicListenerDelayInSeconds", Integer.class);
61         executor = null;
62         getRequest = new HttpGet(UriBuilder.fromUri(env.getProperty("pnf.dmaap.uriPathPrefix"))
63                 .scheme(env.getProperty("pnf.dmaap.protocol"))
64                 .host(env.getProperty("pnf.dmaap.host"))
65                 .port(env.getProperty("pnf.dmaap.port", Integer.class))
66                 .path(env.getProperty("pnf.dmaap.topicName"))
67                 .path(env.getProperty("pnf.dmaap.consumerGroup"))
68                 .path(env.getProperty("pnf.dmaap.consumerId")).build());
69     }
70
71     @Override
72     public synchronized void registerForUpdate(String pnfCorrelationId, Runnable informConsumer) {
73         logger.debug("registering for pnf ready dmaap event for pnf correlation id: {}", pnfCorrelationId);
74         pnfCorrelationIdToThreadMap.put(pnfCorrelationId, informConsumer);
75         if (!dmaapThreadListenerIsRunning) {
76             startDmaapThreadListener();
77         }
78     }
79
80     @Override
81     public synchronized Runnable unregister(String pnfCorrelationId) {
82         logger.debug("unregistering from pnf ready dmaap event for pnf correlation id: {}", pnfCorrelationId);
83         Runnable runnable = pnfCorrelationIdToThreadMap.remove(pnfCorrelationId);
84         if (pnfCorrelationIdToThreadMap.isEmpty()) {
85             stopDmaapThreadListener();
86         }
87         return runnable;
88     }
89
90     private synchronized void startDmaapThreadListener() {
91         if (!dmaapThreadListenerIsRunning) {
92             executor = new ScheduledThreadPoolExecutor(1);
93             executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
94             executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
95             executor.scheduleWithFixedDelay(new DmaapTopicListenerThread(), 0,
96                     topicListenerDelayInSeconds, TimeUnit.SECONDS);
97             dmaapThreadListenerIsRunning = true;
98         }
99     }
100
101     private synchronized void stopDmaapThreadListener() {
102         if (dmaapThreadListenerIsRunning) {
103             executor.shutdown();
104             dmaapThreadListenerIsRunning = false;
105             executor = null;
106         }
107     }
108
109     class DmaapTopicListenerThread implements Runnable {
110
111         @Override
112         public void run() {
113             try {
114                 logger.debug("dmaap listener starts listening pnf ready dmaap topic");
115                 HttpResponse response = httpClient.execute(getRequest);
116                 getPnfCorrelationIdListFromResponse(response).forEach(this::informAboutPnfReadyIfPnfCorrelationIdFound);
117             } catch (IOException e) {
118                 logger.error("Exception caught during sending rest request to dmaap for listening event topic", e);
119             }
120             finally {
121                 getRequest.reset();
122             }
123         }
124
125         private List<String> getPnfCorrelationIdListFromResponse(HttpResponse response) throws IOException {
126             if (response.getStatusLine().getStatusCode() == 200) {
127                 String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
128                 if (responseString != null) {
129                     return JsonUtilForPnfCorrelationId.parseJsonToGelAllPnfCorrelationId(responseString);
130                 }
131             }
132             return Collections.emptyList();
133         }
134
135         private void informAboutPnfReadyIfPnfCorrelationIdFound(String pnfCorrelationId) {
136             Runnable runnable = unregister(pnfCorrelationId);
137             if (runnable != null) {
138                 logger.debug("dmaap listener gets pnf ready event for pnfCorrelationId: {}", pnfCorrelationId);
139                 runnable.run();
140             }
141         }
142     }
143
144 }