353b4e32c5ad78324927a6a35bb5044c7c66afa3
[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.net.URI;
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.Executors;
30 import java.util.concurrent.ScheduledExecutorService;
31 import java.util.concurrent.TimeUnit;
32
33 import javax.ws.rs.core.UriBuilder;
34
35 import org.apache.http.HttpResponse;
36 import org.apache.http.client.HttpClient;
37 import org.apache.http.client.methods.HttpGet;
38 import org.apache.http.impl.client.HttpClientBuilder;
39 import org.apache.http.util.EntityUtils;
40 import org.onap.so.logger.MsoLogger;
41 import org.springframework.beans.factory.annotation.Autowired;
42 import org.springframework.context.annotation.Scope;
43 import org.springframework.core.env.Environment;
44 import org.springframework.stereotype.Component;
45
46 @Component
47 @Scope("prototype")
48 public class PnfEventReadyDmaapClient implements DmaapClient {
49
50     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, PnfEventReadyDmaapClient.class);
51
52     private static final String JSON_PATH_CORRELATION_ID = "$.pnfRegistrationFields.correlationId";
53     
54     @Autowired
55     private Environment env;
56     private HttpClient httpClient;
57     private String dmaapHost;
58     private int dmaapPort;
59     private String dmaapProtocol;
60     private String dmaapUriPathPrefix;
61     private String dmaapTopicName;
62     private String consumerId;
63     private String consumerGroup;
64     private Map<String, Runnable> pnfCorrelationIdToThreadMap;
65     private HttpGet getRequest;
66     private ScheduledExecutorService executor;
67     private int dmaapClientDelayInSeconds;
68     private volatile boolean dmaapThreadListenerIsRunning;
69
70     public void init() {
71         httpClient = HttpClientBuilder.create().build();
72         pnfCorrelationIdToThreadMap = new ConcurrentHashMap<>();
73         dmaapHost = env.getProperty("pnf.dmaap.host");
74         dmaapPort = env.getProperty("pnf.dmaap.port", Integer.class);
75         executor = null;
76         getRequest = new HttpGet(buildURI());
77     }
78
79     @Override
80     public synchronized void registerForUpdate(String correlationId, Runnable informConsumer) {
81         LOGGER.debug("registering for pnf ready dmaap event for correlation id: " + correlationId);
82         pnfCorrelationIdToThreadMap.put(correlationId, informConsumer);
83         if (!dmaapThreadListenerIsRunning) {
84             startDmaapThreadListener();
85         }
86     }
87
88     @Override
89     public synchronized Runnable unregister(String correlationId) {
90         LOGGER.debug("unregistering from pnf ready dmaap event for correlation id: " + correlationId);
91         Runnable runnable = pnfCorrelationIdToThreadMap.remove(correlationId);
92         if (pnfCorrelationIdToThreadMap.isEmpty()) {
93             stopDmaapThreadListener();
94         }
95         return runnable;
96     }
97
98     private synchronized void startDmaapThreadListener() {
99         if (!dmaapThreadListenerIsRunning) {
100             executor = Executors.newScheduledThreadPool(1);
101             executor.scheduleWithFixedDelay(new DmaapTopicListenerThread(), 0,
102                     dmaapClientDelayInSeconds, TimeUnit.SECONDS);
103             dmaapThreadListenerIsRunning = true;
104         }
105     }
106
107     private synchronized void stopDmaapThreadListener() {
108         if (dmaapThreadListenerIsRunning) {
109             executor.shutdownNow();
110             dmaapThreadListenerIsRunning = false;
111             executor = null;
112         }
113     }
114
115     private URI buildURI() {
116         return UriBuilder.fromUri(dmaapUriPathPrefix)
117                 .scheme(dmaapProtocol)
118                 .host(dmaapHost)
119                 .port(dmaapPort).path(dmaapTopicName)
120                 .path(consumerGroup).path(consumerId).build();
121     }
122
123     public void setDmaapProtocol(String dmaapProtocol) {
124         this.dmaapProtocol = dmaapProtocol;
125     }
126
127     public void setDmaapUriPathPrefix(String dmaapUriPathPrefix) {
128         this.dmaapUriPathPrefix = dmaapUriPathPrefix;
129     }
130
131     public void setDmaapTopicName(String dmaapTopicName) {
132         this.dmaapTopicName = dmaapTopicName;
133     }
134
135     public void setConsumerId(String consumerId) {
136         this.consumerId = consumerId;
137     }
138
139     public void setConsumerGroup(String consumerGroup) {
140         this.consumerGroup = consumerGroup;
141     }
142
143     public void setDmaapClientDelayInSeconds(int dmaapClientDelayInSeconds) {
144         this.dmaapClientDelayInSeconds = dmaapClientDelayInSeconds;
145     }
146
147     class DmaapTopicListenerThread implements Runnable {
148
149         @Override
150         public void run() {
151             try {
152                 HttpResponse response = httpClient.execute(getRequest);
153                 getCorrelationIdListFromResponse(response).forEach(this::informAboutPnfReadyIfCorrelationIdFound);
154             } catch (IOException e) {
155                 LOGGER.error("Exception caught during sending rest request to dmaap for listening event topic", e);
156             }
157         }
158
159         private List<String> getCorrelationIdListFromResponse(HttpResponse response) throws IOException {
160             if (response.getStatusLine().getStatusCode() == 200) {
161                 String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
162                 if (responseString != null) {
163                     return JsonUtilForCorrelationId.parseJsonToGelAllCorrelationId(responseString);
164                 }
165             }
166             return Collections.emptyList();
167         }
168
169         private synchronized void informAboutPnfReadyIfCorrelationIdFound(String correlationId) {
170             Runnable runnable = unregister(correlationId);
171             if (runnable != null) {
172                 LOGGER.debug("pnf ready event got from dmaap for correlationId: " + correlationId);
173                 runnable.run();
174             }
175         }
176     }
177
178 }