Merge "Fix the ingestion of mixed resource"
[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     private volatile List<Map<String, String>> listOfUpdateInfoMap;
58
59     @Autowired
60     public PnfEventReadyDmaapClient(Environment env) {
61         httpClient = HttpClientBuilder.create().build();
62         pnfCorrelationIdToThreadMap = new ConcurrentHashMap<>();
63         topicListenerDelayInSeconds = env.getProperty("pnf.dmaap.topicListenerDelayInSeconds", Integer.class);
64         executor = null;
65         getRequest = new HttpGet(UriBuilder.fromUri(env.getProperty("pnf.dmaap.uriPathPrefix"))
66                 .scheme(env.getProperty("pnf.dmaap.protocol")).host(env.getProperty("pnf.dmaap.host"))
67                 .port(env.getProperty("pnf.dmaap.port", Integer.class)).path(env.getProperty("pnf.dmaap.topicName"))
68                 .path(env.getProperty("pnf.dmaap.consumerGroup")).path(env.getProperty("pnf.dmaap.consumerId"))
69                 .build());
70         listOfUpdateInfoMap = new ArrayList<>();
71     }
72
73     @Override
74     public synchronized void registerForUpdate(String pnfCorrelationId, Runnable informConsumer,
75             Map<String, String> updateInfo) {
76         logger.debug("registering for pnf ready dmaap event for pnf correlation id: {}", pnfCorrelationId);
77         synchronized (listOfUpdateInfoMap) {
78             listOfUpdateInfoMap.add(updateInfo);
79         }
80         pnfCorrelationIdToThreadMap.put(pnfCorrelationId, informConsumer);
81         if (!dmaapThreadListenerIsRunning) {
82             startDmaapThreadListener();
83         }
84     }
85
86     @Override
87     public synchronized Runnable unregister(String pnfCorrelationId) {
88         logger.debug("unregistering from pnf ready dmaap event for pnf correlation id: {}", pnfCorrelationId);
89         Runnable runnable = pnfCorrelationIdToThreadMap.remove(pnfCorrelationId);
90         synchronized (listOfUpdateInfoMap) {
91             for (int i = listOfUpdateInfoMap.size() - 1; i >= 0; i--) {
92                 if (!listOfUpdateInfoMap.get(i).containsKey("pnfCorrelationId"))
93                     continue;
94                 String id = listOfUpdateInfoMap.get(i).get("pnfCorrelationId");
95                 if (id != pnfCorrelationId)
96                     continue;
97                 listOfUpdateInfoMap.remove(i);
98             }
99         }
100         if (pnfCorrelationIdToThreadMap.isEmpty()) {
101             stopDmaapThreadListener();
102         }
103         return runnable;
104     }
105
106     private synchronized void startDmaapThreadListener() {
107         if (!dmaapThreadListenerIsRunning) {
108             executor = new ScheduledThreadPoolExecutor(1);
109             executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
110             executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
111             executor.scheduleWithFixedDelay(new DmaapTopicListenerThread(), 0, topicListenerDelayInSeconds,
112                     TimeUnit.SECONDS);
113             dmaapThreadListenerIsRunning = true;
114         }
115     }
116
117     private synchronized void stopDmaapThreadListener() {
118         if (dmaapThreadListenerIsRunning) {
119             executor.shutdown();
120             dmaapThreadListenerIsRunning = false;
121             executor = null;
122         }
123     }
124
125     class DmaapTopicListenerThread implements Runnable {
126
127         @Override
128         public void run() {
129             try {
130                 logger.debug("dmaap listener starts listening pnf ready dmaap topic");
131                 HttpResponse response = httpClient.execute(getRequest);
132                 List<String> idList = getPnfCorrelationIdListFromResponse(response);
133
134                 // idList is never null
135                 if (!idList.isEmpty()) {
136                     // send only body of response
137                     registerClientResponse(idList.get(0), EntityUtils.toString(response.getEntity(), "UTF-8"));
138                 }
139
140                 if (idList != null) {
141                     idList.forEach(this::informAboutPnfReadyIfPnfCorrelationIdFound);
142                 }
143             } catch (IOException e) {
144                 logger.error("Exception caught during sending rest request to dmaap for listening event topic", e);
145             } finally {
146                 getRequest.reset();
147             }
148         }
149
150         private List<String> getPnfCorrelationIdListFromResponse(HttpResponse response) throws IOException {
151             if (response.getStatusLine().getStatusCode() == 200) {
152                 String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
153                 if (responseString != null) {
154                     return JsonUtilForPnfCorrelationId.parseJsonToGelAllPnfCorrelationId(responseString);
155                 }
156             }
157             return Collections.emptyList();
158         }
159
160         private void informAboutPnfReadyIfPnfCorrelationIdFound(String pnfCorrelationId) {
161             Runnable runnable = unregister(pnfCorrelationId);
162             if (runnable != null) {
163                 logger.debug("dmaap listener gets pnf ready event for pnfCorrelationId: {}", pnfCorrelationId);
164                 runnable.run();
165             }
166         }
167
168         private void registerClientResponse(String pnfCorrelationId, String response) {
169
170             String customerId = null;
171             String serviceType = null;
172             String serId = null;
173             synchronized (listOfUpdateInfoMap) {
174                 for (Map<String, String> map : listOfUpdateInfoMap) {
175                     if (!map.containsKey("pnfCorrelationId"))
176                         continue;
177                     if (pnfCorrelationId != map.get("pnfCorrelationId"))
178                         continue;
179                     if (!map.containsKey("globalSubscriberID"))
180                         continue;
181                     if (!map.containsKey("serviceType"))
182                         continue;
183                     if (!map.containsKey("serviceInstanceId"))
184                         continue;
185                     customerId = map.get("pnfCorrelationId");
186                     serviceType = map.get("serviceType");
187                     serId = map.get("serviceInstanceId");
188                 }
189             }
190             if (customerId == null || serviceType == null || serId == null)
191                 return;
192             AAIResourcesClient client = new AAIResourcesClient();
193             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE_METADATA, customerId,
194                     serviceType, serId);
195             client.update(uri, response);
196         }
197
198     }
199 }