Merge "Implement interface to SDC for ActivitySpec"
[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.Collections;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ScheduledThreadPoolExecutor;
31 import java.util.concurrent.TimeUnit;
32 import javax.ws.rs.core.UriBuilder;
33 import org.apache.http.HttpResponse;
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.onap.so.bpmn.infrastructure.pnf.PnfNotificationEvent;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.springframework.beans.factory.annotation.Autowired;
42 import org.springframework.context.ApplicationEventPublisher;
43 import org.springframework.core.env.Environment;
44 import org.springframework.stereotype.Component;
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     private ApplicationEventPublisher applicationEventPublisher;
59
60     @Autowired
61     public PnfEventReadyDmaapClient(Environment env, ApplicationEventPublisher applicationEventPublisher) {
62         this.applicationEventPublisher = applicationEventPublisher;
63         httpClient = HttpClientBuilder.create().build();
64         pnfCorrelationIdToThreadMap = new ConcurrentHashMap<>();
65         topicListenerDelayInSeconds = env.getProperty("pnf.dmaap.topicListenerDelayInSeconds", Integer.class);
66         executor = null;
67         getRequest = 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)).path(env.getProperty("pnf.dmaap.topicName"))
70                 .path(env.getProperty("pnf.dmaap.consumerGroup")).path(env.getProperty("pnf.dmaap.consumerId"))
71                 .build());
72     }
73
74     @Override
75     public synchronized void registerForUpdate(String pnfCorrelationId, Runnable informConsumer) {
76         logger.debug("registering for pnf ready dmaap event for pnf correlation id: {}", pnfCorrelationId);
77         pnfCorrelationIdToThreadMap.put(pnfCorrelationId, informConsumer);
78         if (!dmaapThreadListenerIsRunning) {
79             startDmaapThreadListener();
80         }
81     }
82
83     @Override
84     public synchronized Runnable unregister(String pnfCorrelationId) {
85         logger.debug("unregistering from pnf ready dmaap event for pnf correlation id: {}", pnfCorrelationId);
86         Runnable runnable = pnfCorrelationIdToThreadMap.remove(pnfCorrelationId);
87         if (pnfCorrelationIdToThreadMap.isEmpty()) {
88             stopDmaapThreadListener();
89         }
90         return runnable;
91     }
92
93     private synchronized void startDmaapThreadListener() {
94         if (!dmaapThreadListenerIsRunning) {
95             executor = new ScheduledThreadPoolExecutor(1);
96             executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
97             executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
98             executor.scheduleWithFixedDelay(new DmaapTopicListenerThread(), 0, topicListenerDelayInSeconds,
99                     TimeUnit.SECONDS);
100             dmaapThreadListenerIsRunning = true;
101         }
102     }
103
104     private synchronized void stopDmaapThreadListener() {
105         if (dmaapThreadListenerIsRunning) {
106             executor.shutdown();
107             dmaapThreadListenerIsRunning = false;
108             executor = null;
109         }
110     }
111
112     class DmaapTopicListenerThread implements Runnable {
113
114         @Override
115         public void run() {
116             try {
117                 logger.debug("dmaap listener starts listening pnf ready dmaap topic");
118                 HttpResponse response = httpClient.execute(getRequest);
119                 getPnfCorrelationIdListFromResponse(response).forEach(this::informAboutPnfReadyIfPnfCorrelationIdFound);
120             } catch (IOException e) {
121                 logger.error("Exception caught during sending rest request to dmaap for listening event topic", e);
122             } finally {
123                 getRequest.reset();
124             }
125         }
126
127         private List<String> getPnfCorrelationIdListFromResponse(HttpResponse response) throws IOException {
128             if (response.getStatusLine().getStatusCode() == 200) {
129                 String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
130                 if (responseString != null) {
131                     return JsonUtilForPnfCorrelationId.parseJsonToGelAllPnfCorrelationId(responseString);
132                 }
133             }
134             return Collections.emptyList();
135         }
136
137         private void informAboutPnfReadyIfPnfCorrelationIdFound(String pnfCorrelationId) {
138             unregister(pnfCorrelationId);
139             PnfNotificationEvent pnfNotificationEvent = new PnfNotificationEvent(this, pnfCorrelationId);
140             applicationEventPublisher.publishEvent(pnfNotificationEvent);
141         }
142     }
143 }