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