PnfReadyEventConsumer implementation
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / java / org / openecomp / mso / 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  * 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.openecomp.mso.bpmn.infrastructure.pnf.dmaap;
22
23 import java.io.IOException;
24 import java.net.URI;
25 import java.util.Map;
26 import java.util.Optional;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.Executors;
29 import java.util.concurrent.ScheduledExecutorService;
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.openecomp.mso.jsonpath.JsonPathUtil;
38 import org.openecomp.mso.logger.MsoLogger;
39
40 public class PnfEventReadyDmaapClient implements DmaapClient {
41
42     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
43
44     private static final String JSON_PATH_CORRELATION_ID = "$.pnfRegistrationFields.correlationId";
45     private HttpClient httpClient;
46     private String dmaapHost;
47     private int dmaapPort;
48     private String dmaapProtocol;
49     private String dmaapUriPathPrefix;
50     private String dmaapTopicName;
51     private String consumerId;
52     private String consumerGroup;
53     private Map<String, Runnable> pnfCorrelationIdToThreadMap;
54     private HttpGet getRequest;
55     private ScheduledExecutorService executor;
56     private int dmaapClientDelayInSeconds;
57     private volatile boolean dmaapThreadListenerIsRunning;
58
59     public PnfEventReadyDmaapClient() {
60         httpClient = HttpClientBuilder.create().build();
61         pnfCorrelationIdToThreadMap = new ConcurrentHashMap<>();
62         executor = null;
63     }
64
65     public void init() {
66         getRequest = new HttpGet(buildURI());
67     }
68
69     @Override
70     public synchronized void registerForUpdate(String correlationId, Runnable informConsumer) {
71         pnfCorrelationIdToThreadMap.put(correlationId, informConsumer);
72         if (!dmaapThreadListenerIsRunning) {
73             startDmaapThreadListener();
74         }
75     }
76
77     @Override
78     public synchronized Runnable unregister(String correlationId) {
79         Runnable runnable = pnfCorrelationIdToThreadMap.remove(correlationId);
80         if (pnfCorrelationIdToThreadMap.isEmpty()) {
81             stopDmaapThreadListener();
82         }
83         return runnable;
84     }
85
86     private synchronized void startDmaapThreadListener() {
87         if (!dmaapThreadListenerIsRunning) {
88             executor = Executors.newScheduledThreadPool(1);
89             executor.scheduleWithFixedDelay(new DmaapTopicListenerThread(), 0,
90                     dmaapClientDelayInSeconds, TimeUnit.SECONDS);
91             dmaapThreadListenerIsRunning = true;
92         }
93     }
94
95     private synchronized void stopDmaapThreadListener() {
96         if (dmaapThreadListenerIsRunning) {
97             executor.shutdownNow();
98             dmaapThreadListenerIsRunning = false;
99             executor = null;
100         }
101     }
102
103     private URI buildURI() {
104         return UriBuilder.fromUri(dmaapUriPathPrefix)
105                 .scheme(dmaapProtocol)
106                 .host(dmaapHost)
107                 .port(dmaapPort).path(dmaapTopicName)
108                 .path(consumerGroup).path(consumerId).build();
109     }
110
111     public void setDmaapHost(String dmaapHost) {
112         this.dmaapHost = dmaapHost;
113     }
114
115     public void setDmaapPort(int dmaapPort) {
116         this.dmaapPort = dmaapPort;
117     }
118
119     public void setDmaapProtocol(String dmaapProtocol) {
120         this.dmaapProtocol = dmaapProtocol;
121     }
122
123     public void setDmaapUriPathPrefix(String dmaapUriPathPrefix) {
124         this.dmaapUriPathPrefix = dmaapUriPathPrefix;
125     }
126
127     public void setDmaapTopicName(String dmaapTopicName) {
128         this.dmaapTopicName = dmaapTopicName;
129     }
130
131     public void setConsumerId(String consumerId) {
132         this.consumerId = consumerId;
133     }
134
135     public void setConsumerGroup(String consumerGroup) {
136         this.consumerGroup = consumerGroup;
137     }
138
139     public void setDmaapClientDelayInSeconds(int dmaapClientDelayInSeconds) {
140         this.dmaapClientDelayInSeconds = dmaapClientDelayInSeconds;
141     }
142
143     class DmaapTopicListenerThread implements Runnable {
144
145         @Override
146         public void run() {
147             try {
148                 HttpResponse response = httpClient.execute(getRequest);
149                 getCorrelationIdFromResponse(response).ifPresent(this::informAboutPnfReadyIfCorrelationIdFound);
150             } catch (IOException e) {
151                 LOGGER.error("Exception caught during sending rest request to dmaap for listening event topic", e);
152             }
153         }
154
155         private Optional<String> getCorrelationIdFromResponse(HttpResponse response) throws IOException {
156             if (response.getStatusLine().getStatusCode() == 200) {
157                 String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
158                 if (responseString != null) {
159                     return JsonPathUtil.getInstance().locateResult(responseString, JSON_PATH_CORRELATION_ID);
160                 }
161             }
162             return Optional.empty();
163         }
164
165         private synchronized void informAboutPnfReadyIfCorrelationIdFound(String correlationId) {
166             Runnable runnable = unregister(correlationId);
167             if (runnable != null) {
168                 runnable.run();
169             }
170         }
171     }
172
173 }