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