Merge "Sonar fix NullPointerException"
[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.*;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ScheduledThreadPoolExecutor;
29 import java.util.concurrent.TimeUnit;
30 import javax.ws.rs.core.UriBuilder;
31 import org.apache.http.HttpResponse;
32 import org.apache.http.client.HttpClient;
33 import org.apache.http.client.methods.HttpGet;
34 import org.apache.http.impl.client.HttpClientBuilder;
35 import org.apache.http.util.EntityUtils;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.springframework.beans.factory.annotation.Autowired;
39 import org.springframework.core.env.Environment;
40 import org.springframework.stereotype.Component;
41 import org.onap.so.client.aai.entities.uri.AAIResourceUri;
42 import org.onap.so.client.aai.entities.uri.AAIUriFactory;
43 import org.onap.so.client.aai.AAIResourcesClient;
44 import org.onap.so.client.aai.AAIObjectType;
45
46 @Component
47 public class PnfEventReadyDmaapClient implements DmaapClient {
48
49     private static final Logger logger = LoggerFactory.getLogger(PnfEventReadyDmaapClient.class);
50
51     private HttpClient httpClient;
52     private Map<String, Runnable> pnfCorrelationIdToThreadMap;
53     private HttpGet getRequest;
54     private int topicListenerDelayInSeconds;
55     private volatile ScheduledThreadPoolExecutor executor;
56     private volatile boolean dmaapThreadListenerIsRunning;
57
58     public volatile List<HashMap<String, String>> updateInfoMap;
59
60     @Autowired
61     public PnfEventReadyDmaapClient(Environment env) {
62         httpClient = HttpClientBuilder.create().build();
63         pnfCorrelationIdToThreadMap = new ConcurrentHashMap<>();
64         topicListenerDelayInSeconds = env.getProperty("pnf.dmaap.topicListenerDelayInSeconds", Integer.class);
65         executor = null;
66         getRequest = new HttpGet(UriBuilder.fromUri(env.getProperty("pnf.dmaap.uriPathPrefix"))
67                 .scheme(env.getProperty("pnf.dmaap.protocol")).host(env.getProperty("pnf.dmaap.host"))
68                 .port(env.getProperty("pnf.dmaap.port", Integer.class)).path(env.getProperty("pnf.dmaap.topicName"))
69                 .path(env.getProperty("pnf.dmaap.consumerGroup")).path(env.getProperty("pnf.dmaap.consumerId"))
70                 .build());
71         updateInfoMap = new ArrayList<>();
72     }
73
74     @Override
75     public synchronized void registerForUpdate(String pnfCorrelationId, Runnable informConsumer,
76             Optional<HashMap<String, String>> updateInfo) {
77         logger.debug("registering for pnf ready dmaap event for pnf correlation id: {}", pnfCorrelationId);
78         HashMap<String, String> map = updateInfo.get();
79         if (map != null && map.size() > 0) {
80             synchronized (updateInfoMap) {
81                 updateInfoMap.add(map);
82             }
83         }
84         pnfCorrelationIdToThreadMap.put(pnfCorrelationId, informConsumer);
85         if (!dmaapThreadListenerIsRunning) {
86             startDmaapThreadListener();
87         }
88     }
89
90     @Override
91     public synchronized Runnable unregister(String pnfCorrelationId) {
92         logger.debug("unregistering from pnf ready dmaap event for pnf correlation id: {}", pnfCorrelationId);
93         Runnable runnable = runnable = pnfCorrelationIdToThreadMap.remove(pnfCorrelationId);
94         synchronized (updateInfoMap) {
95             for (int i = updateInfoMap.size() - 1; i >= 0; i--) {
96                 if (!updateInfoMap.get(i).containsKey("pnfCorrelationId"))
97                     continue;
98                 String id = updateInfoMap.get(i).get("pnfCorrelationId");
99                 if (id != pnfCorrelationId)
100                     continue;
101                 updateInfoMap.remove(i);
102             }
103         }
104         if (pnfCorrelationIdToThreadMap.isEmpty()) {
105             stopDmaapThreadListener();
106         }
107         return runnable;
108     }
109
110     private synchronized void startDmaapThreadListener() {
111         if (!dmaapThreadListenerIsRunning) {
112             executor = new ScheduledThreadPoolExecutor(1);
113             executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
114             executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
115             executor.scheduleWithFixedDelay(new DmaapTopicListenerThread(), 0, topicListenerDelayInSeconds,
116                     TimeUnit.SECONDS);
117             dmaapThreadListenerIsRunning = true;
118         }
119     }
120
121     private synchronized void stopDmaapThreadListener() {
122         if (dmaapThreadListenerIsRunning) {
123             executor.shutdown();
124             dmaapThreadListenerIsRunning = false;
125             executor = null;
126         }
127     }
128
129     class DmaapTopicListenerThread implements Runnable {
130
131         @Override
132         public void run() {
133             try {
134                 logger.debug("dmaap listener starts listening pnf ready dmaap topic");
135                 HttpResponse response = httpClient.execute(getRequest);
136                 List<String> idList = getPnfCorrelationIdListFromResponse(response);
137
138                 if (idList != null && idList.size() > 0) {
139                     // send only body of response
140                     registerClientResponse(idList.get(0), EntityUtils.toString(response.getEntity(), "UTF-8"));
141                 }
142
143                 if (idList != null) {
144                     idList.forEach(this::informAboutPnfReadyIfPnfCorrelationIdFound);
145                 }
146             } catch (IOException e) {
147                 logger.error("Exception caught during sending rest request to dmaap for listening event topic", e);
148             } finally {
149                 getRequest.reset();
150             }
151         }
152
153         private List<String> getPnfCorrelationIdListFromResponse(HttpResponse response) throws IOException {
154             if (response.getStatusLine().getStatusCode() == 200) {
155                 String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
156                 if (responseString != null) {
157                     return JsonUtilForPnfCorrelationId.parseJsonToGelAllPnfCorrelationId(responseString);
158                 }
159             }
160             return Collections.emptyList();
161         }
162
163         private void informAboutPnfReadyIfPnfCorrelationIdFound(String pnfCorrelationId) {
164             Runnable runnable = unregister(pnfCorrelationId);
165             if (runnable != null) {
166                 logger.debug("dmaap listener gets pnf ready event for pnfCorrelationId: {}", pnfCorrelationId);
167                 runnable.run();
168             }
169         }
170
171         private void registerClientResponse(String pnfCorrelationId, String response) {
172
173             String customerId = null;
174             String serviceType = null;
175             String serId = null;
176             synchronized (updateInfoMap) {
177                 for (HashMap<String, String> map : updateInfoMap) {
178                     if (!map.containsKey("pnfCorrelationId"))
179                         continue;
180                     if (pnfCorrelationId != map.get("pnfCorrelationId"))
181                         continue;
182                     if (!map.containsKey("globalSubscriberID"))
183                         continue;
184                     if (!map.containsKey("serviceType"))
185                         continue;
186                     if (!map.containsKey("serviceInstanceId"))
187                         continue;
188                     customerId = map.get("pnfCorrelationId");
189                     serviceType = map.get("serviceType");
190                     serId = map.get("serviceInstanceId");
191                 }
192             }
193             if (customerId == null || serviceType == null || serId == null)
194                 return;
195             AAIResourcesClient client = new AAIResourcesClient();
196             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE_METADATA, customerId,
197                     serviceType, serId);
198             client.update(uri, response);
199         }
200
201     }
202 }