518d7ff194d032cf2eb394af33f41212eefe8172
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.pnf.dmaap;
22
23 import java.io.IOException;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.Map;
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.onap.so.logger.MsoLogger;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.core.env.Environment;
39 import org.springframework.stereotype.Component;
40
41 @Component
42 public class PnfEventReadyDmaapClient implements DmaapClient {
43
44     private static final MsoLogger LOGGER = MsoLogger
45             .getMsoLogger(MsoLogger.Catalog.RA, PnfEventReadyDmaapClient.class);
46
47     private HttpClient httpClient;
48     private Map<String, Runnable> pnfCorrelationIdToThreadMap;
49     private HttpGet getRequest;
50     private int topicListenerDelayInSeconds;
51     private volatile ScheduledThreadPoolExecutor executor;
52     private volatile boolean dmaapThreadListenerIsRunning;
53
54     @Autowired
55     public PnfEventReadyDmaapClient(Environment env) {
56         httpClient = HttpClientBuilder.create().build();
57         pnfCorrelationIdToThreadMap = new ConcurrentHashMap<>();
58         topicListenerDelayInSeconds = env.getProperty("pnf.dmaap.topicListenerDelayInSeconds", Integer.class);
59         executor = null;
60         getRequest = new HttpGet(UriBuilder.fromUri(env.getProperty("pnf.dmaap.uriPathPrefix"))
61                 .scheme(env.getProperty("pnf.dmaap.protocol"))
62                 .host(env.getProperty("pnf.dmaap.host"))
63                 .port(env.getProperty("pnf.dmaap.port", Integer.class))
64                 .path(env.getProperty("pnf.dmaap.topicName"))
65                 .path(env.getProperty("pnf.dmaap.consumerGroup"))
66                 .path(env.getProperty("pnf.dmaap.consumerId")).build());
67     }
68
69     @Override
70     public synchronized void registerForUpdate(String correlationId, Runnable informConsumer) {
71         LOGGER.debug("registering for pnf ready dmaap event for correlation id: " + correlationId);
72         pnfCorrelationIdToThreadMap.put(correlationId, informConsumer);
73         if (!dmaapThreadListenerIsRunning) {
74             startDmaapThreadListener();
75         }
76     }
77
78     @Override
79     public synchronized Runnable unregister(String correlationId) {
80         LOGGER.debug("unregistering from pnf ready dmaap event for correlation id: " + correlationId);
81         Runnable runnable = pnfCorrelationIdToThreadMap.remove(correlationId);
82         if (pnfCorrelationIdToThreadMap.isEmpty()) {
83             stopDmaapThreadListener();
84         }
85         return runnable;
86     }
87
88     private synchronized void startDmaapThreadListener() {
89         if (!dmaapThreadListenerIsRunning) {
90             executor = new ScheduledThreadPoolExecutor(1);
91             executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
92             executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
93             executor.scheduleWithFixedDelay(new DmaapTopicListenerThread(), 0,
94                     topicListenerDelayInSeconds, TimeUnit.SECONDS);
95             dmaapThreadListenerIsRunning = true;
96         }
97     }
98
99     private synchronized void stopDmaapThreadListener() {
100         if (dmaapThreadListenerIsRunning) {
101             executor.shutdown();
102             dmaapThreadListenerIsRunning = false;
103             executor = null;
104         }
105     }
106
107     class DmaapTopicListenerThread implements Runnable {
108
109         @Override
110         public void run() {
111             try {
112                 HttpResponse response = httpClient.execute(getRequest);
113                 getCorrelationIdListFromResponse(response).forEach(this::informAboutPnfReadyIfCorrelationIdFound);
114             } catch (IOException e) {
115                 LOGGER.error("Exception caught during sending rest request to dmaap for listening event topic", e);
116             }
117         }
118
119         private List<String> getCorrelationIdListFromResponse(HttpResponse response) throws IOException {
120             if (response.getStatusLine().getStatusCode() == 200) {
121                 String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
122                 if (responseString != null) {
123                     return JsonUtilForCorrelationId.parseJsonToGelAllCorrelationId(responseString);
124                 }
125             }
126             return Collections.emptyList();
127         }
128
129         private void informAboutPnfReadyIfCorrelationIdFound(String correlationId) {
130             Runnable runnable = unregister(correlationId);
131             if (runnable != null) {
132                 LOGGER.debug("pnf ready event got from dmaap for correlationId: " + correlationId);
133                 runnable.run();
134             }
135         }
136     }
137
138 }