a2c73ca639ae2c89f3bc10aed0d2d45d39699fa2
[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")).host(env.getProperty("pnf.dmaap.host"))
64                 .port(env.getProperty("pnf.dmaap.port", Integer.class)).path(env.getProperty("pnf.dmaap.topicName"))
65                 .path(env.getProperty("pnf.dmaap.consumerGroup")).path(env.getProperty("pnf.dmaap.consumerId"))
66                 .build());
67     }
68
69     @Override
70     public synchronized void registerForUpdate(String pnfCorrelationId, Runnable informConsumer) {
71         logger.debug("registering for pnf ready dmaap event for pnf correlation id: {}", pnfCorrelationId);
72         pnfCorrelationIdToThreadMap.put(pnfCorrelationId, informConsumer);
73         if (!dmaapThreadListenerIsRunning) {
74             startDmaapThreadListener();
75         }
76     }
77
78     @Override
79     public synchronized Runnable unregister(String pnfCorrelationId) {
80         logger.debug("unregistering from pnf ready dmaap event for pnf correlation id: {}", pnfCorrelationId);
81         Runnable runnable = pnfCorrelationIdToThreadMap.remove(pnfCorrelationId);
82         if (pnfCorrelationIdToThreadMap.isEmpty()) {
83             stopDmaapThreadListener();
84         }
85         return runnable;
86     }
87
88     private synchronized void startDmaapThreadListener() {
89         if (!dmaapThreadListenerIsRunning) {
90             executor = new ScheduledThreadPoolExecutor(1);
91             executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
92             executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
93             executor.scheduleWithFixedDelay(new DmaapTopicListenerThread(), 0, topicListenerDelayInSeconds,
94                     TimeUnit.SECONDS);
95             dmaapThreadListenerIsRunning = true;
96         }
97     }
98
99     private synchronized void stopDmaapThreadListener() {
100         if (dmaapThreadListenerIsRunning) {
101             executor.shutdown();
102             dmaapThreadListenerIsRunning = false;
103             executor = null;
104         }
105     }
106
107     class DmaapTopicListenerThread implements Runnable {
108
109         @Override
110         public void run() {
111             try {
112                 logger.debug("dmaap listener starts listening pnf ready dmaap topic");
113                 HttpResponse response = httpClient.execute(getRequest);
114                 getPnfCorrelationIdListFromResponse(response).forEach(this::informAboutPnfReadyIfPnfCorrelationIdFound);
115             } catch (IOException e) {
116                 logger.error("Exception caught during sending rest request to dmaap for listening event topic", e);
117             } finally {
118                 getRequest.reset();
119             }
120         }
121
122         private List<String> getPnfCorrelationIdListFromResponse(HttpResponse response) throws IOException {
123             if (response.getStatusLine().getStatusCode() == 200) {
124                 String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
125                 if (responseString != null) {
126                     return JsonUtilForPnfCorrelationId.parseJsonToGelAllPnfCorrelationId(responseString);
127                 }
128             }
129             return Collections.emptyList();
130         }
131
132         private void informAboutPnfReadyIfPnfCorrelationIdFound(String pnfCorrelationId) {
133             Runnable runnable = unregister(pnfCorrelationId);
134             if (runnable != null) {
135                 logger.debug("dmaap listener gets pnf ready event for pnfCorrelationId: {}", pnfCorrelationId);
136                 runnable.run();
137             }
138         }
139     }
140
141 }