Add or Delete a PNF to an Active Service
[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
54
55
56     @Autowired
57     public PnfEventReadyDmaapClient(Environment env) {
58         httpClient = HttpClientBuilder.create().build();
59         pnfCorrelationIdToThreadMap = new ConcurrentHashMap<>();
60         topicListenerDelayInSeconds = env.getProperty("pnf.dmaap.topicListenerDelayInSeconds", Integer.class);
61         executor = null;
62         getRequestForpnfReady = new HttpGet(UriBuilder.fromUri(env.getProperty("pnf.dmaap.uriPathPrefix"))
63                 .scheme(env.getProperty("pnf.dmaap.protocol")).host(env.getProperty("pnf.dmaap.host"))
64                 .port(env.getProperty("pnf.dmaap.port", Integer.class))
65                 .path(env.getProperty("pnf.dmaap.pnfReadyTopicName")).path(env.getProperty("pnf.dmaap.consumerGroup"))
66                 .path(env.getProperty("pnf.dmaap.consumerId")).build());
67         getRequestForPnfUpdate = new HttpGet(UriBuilder.fromUri(env.getProperty("pnf.dmaap.uriPathPrefix"))
68                 .scheme(env.getProperty("pnf.dmaap.protocol")).host(env.getProperty("pnf.dmaap.host"))
69                 .port(env.getProperty("pnf.dmaap.port", Integer.class))
70                 .path(env.getProperty("pnf.dmaap.pnfUpdateTopicName")).path(env.getProperty("pnf.dmaap.consumerGroup"))
71                 .path(env.getProperty("pnf.dmaap.consumerIdUpdate")).build());
72     }
73
74
75     @Override
76     public synchronized void registerForUpdate(String pnfCorrelationId, Runnable informConsumer) {
77         logger.debug("registering for pnf ready dmaap event for pnf correlation id: {}", pnfCorrelationId);
78         pnfCorrelationIdToThreadMap.put(pnfCorrelationId, informConsumer);
79         if (!dmaapThreadListenerIsRunning) {
80             startDmaapThreadListener();
81         }
82     }
83
84     @Override
85     public synchronized Runnable unregister(String pnfCorrelationId) {
86         logger.debug("unregistering from pnf ready dmaap event for pnf correlation id: {}", pnfCorrelationId);
87         Runnable runnable = pnfCorrelationIdToThreadMap.remove(pnfCorrelationId);
88         if (pnfCorrelationIdToThreadMap.isEmpty()) {
89             stopDmaapThreadListener();
90         }
91         return runnable;
92     }
93
94     private synchronized void startDmaapThreadListener() {
95         if (!dmaapThreadListenerIsRunning) {
96             executor = new ScheduledThreadPoolExecutor(1);
97             executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
98             executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
99             executor.scheduleWithFixedDelay(new DmaapTopicListenerThread(), 0, topicListenerDelayInSeconds,
100                     TimeUnit.SECONDS);
101             dmaapThreadListenerIsRunning = true;
102         }
103     }
104
105     private synchronized void stopDmaapThreadListener() {
106         if (dmaapThreadListenerIsRunning) {
107             executor.shutdown();
108             dmaapThreadListenerIsRunning = false;
109             executor = null;
110         }
111     }
112
113     class DmaapTopicListenerThread implements Runnable {
114         @Override
115         public void run() {
116             try {
117                 HttpResponse response;
118                 response = httpClient.execute(getRequestForPnfUpdate);
119                 List<String> pnfUpdateResponse = getPnfCorrelationIdListFromResponse(response);
120                 if (pnfUpdateResponse.isEmpty()) {
121                     response = httpClient.execute(getRequestForpnfReady);
122                     getPnfCorrelationIdListFromResponse(response)
123                             .forEach(this::informAboutPnfReadyIfPnfCorrelationIdFound);
124                 } else {
125                     pnfUpdateResponse.forEach(this::informAboutPnfReadyIfPnfCorrelationIdFound);
126                 }
127             } catch (IOException e) {
128                 logger.error("Exception caught during sending rest request to dmaap for listening event topic", e);
129             } finally {
130                 getRequestForpnfReady.reset();
131                 getRequestForPnfUpdate.reset();
132             }
133         }
134
135         private List<String> getPnfCorrelationIdListFromResponse(HttpResponse response) throws IOException {
136             if (response.getStatusLine().getStatusCode() == 200) {
137                 String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
138                 if (responseString != null) {
139                     return JsonUtilForPnfCorrelationId.parseJsonToGelAllPnfCorrelationId(responseString);
140                 }
141             }
142             return Collections.emptyList();
143         }
144
145         private void informAboutPnfReadyIfPnfCorrelationIdFound(String pnfCorrelationId) {
146             Runnable runnable = unregister(pnfCorrelationId);
147             if (runnable != null) {
148                 logger.debug("dmaap listener gets pnf ready event for pnfCorrelationId: {}", pnfCorrelationId);
149                 runnable.run();
150             }
151         }
152     }
153 }
154