Merge "Removed duplicate use of networkType field in String.format() call to prevent...
[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 = 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                 // idList is never null
139                 if (!idList.isEmpty()) {
140                     // send only body of response
141                     registerClientResponse(idList.get(0), EntityUtils.toString(response.getEntity(), "UTF-8"));
142                 }
143
144                 if (idList != null) {
145                     idList.forEach(this::informAboutPnfReadyIfPnfCorrelationIdFound);
146                 }
147             } catch (IOException e) {
148                 logger.error("Exception caught during sending rest request to dmaap for listening event topic", e);
149             } finally {
150                 getRequest.reset();
151             }
152         }
153
154         private List<String> getPnfCorrelationIdListFromResponse(HttpResponse response) throws IOException {
155             if (response.getStatusLine().getStatusCode() == 200) {
156                 String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
157                 if (responseString != null) {
158                     return JsonUtilForPnfCorrelationId.parseJsonToGelAllPnfCorrelationId(responseString);
159                 }
160             }
161             return Collections.emptyList();
162         }
163
164         private void informAboutPnfReadyIfPnfCorrelationIdFound(String pnfCorrelationId) {
165             Runnable runnable = unregister(pnfCorrelationId);
166             if (runnable != null) {
167                 logger.debug("dmaap listener gets pnf ready event for pnfCorrelationId: {}", pnfCorrelationId);
168                 runnable.run();
169             }
170         }
171
172         private void registerClientResponse(String pnfCorrelationId, String response) {
173
174             String customerId = null;
175             String serviceType = null;
176             String serId = null;
177             synchronized (updateInfoMap) {
178                 for (HashMap<String, String> map : updateInfoMap) {
179                     if (!map.containsKey("pnfCorrelationId"))
180                         continue;
181                     if (pnfCorrelationId != map.get("pnfCorrelationId"))
182                         continue;
183                     if (!map.containsKey("globalSubscriberID"))
184                         continue;
185                     if (!map.containsKey("serviceType"))
186                         continue;
187                     if (!map.containsKey("serviceInstanceId"))
188                         continue;
189                     customerId = map.get("pnfCorrelationId");
190                     serviceType = map.get("serviceType");
191                     serId = map.get("serviceInstanceId");
192                 }
193             }
194             if (customerId == null || serviceType == null || serId == null)
195                 return;
196             AAIResourcesClient client = new AAIResourcesClient();
197             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE_METADATA, customerId,
198                     serviceType, serId);
199             client.update(uri, response);
200         }
201
202     }
203 }