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