1fd2de97f2237f443d1c156c2993766c20dc7ef8
[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.openecomp.mso.bpmn.infrastructure.pnf.dmaap;
22
23 import com.google.common.annotations.VisibleForTesting;
24 import java.io.IOException;
25 import java.net.URI;
26 import java.util.Map;
27 import java.util.Optional;
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.jsonpath.JsonPathUtil;
39 import org.openecomp.mso.logger.MsoLogger;
40
41 public class PnfEventReadyConsumer implements DmaapClient {
42
43     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
44
45     private static final String JSON_PATH_CORRELATION_ID = "$.pnfRegistrationFields.correlationId";
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 PnfEventReadyConsumer() {
61         httpClient = HttpClientBuilder.create().build();
62         pnfCorrelationIdToThreadMap = new ConcurrentHashMap<>();
63         executor = null;
64     }
65
66     public void init() {
67         getRequest = new HttpGet(buildURI());
68     }
69
70     //TODO: extract this logic to separate class and test it there to avoid using VisibleForTesting
71     @VisibleForTesting
72     void sendRequest() {
73         try {
74             HttpResponse response = httpClient.execute(getRequest);
75             getCorrelationIdFromResponse(response).ifPresent(this::informAboutPnfReadyIfCorrelationIdFound);
76         } catch (IOException e) {
77             LOGGER.error("Exception caught during sending rest request to dmaap for listening event topic", e);
78         }
79     }
80
81     @Override
82     public synchronized void registerForUpdate(String correlationId, Runnable informConsumer) {
83         pnfCorrelationIdToThreadMap.put(correlationId, informConsumer);
84         if (!dmaapThreadListenerIsRunning) {
85             startDmaapThreadListener();
86         }
87     }
88
89     @Override
90     public synchronized Runnable unregister(String 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(this::sendRequest, 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     private Optional<String> getCorrelationIdFromResponse(HttpResponse response) throws IOException {
124         if (response.getStatusLine().getStatusCode() == 200) {
125             String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
126             if (responseString != null) {
127                 return JsonPathUtil.getInstance().locateResult(responseString, JSON_PATH_CORRELATION_ID);
128             }
129         }
130         return Optional.empty();
131     }
132
133
134     private synchronized void informAboutPnfReadyIfCorrelationIdFound(String correlationId) {
135         Runnable runnable = unregister(correlationId);
136         if (runnable != null) {
137             runnable.run();
138         }
139     }
140
141     public void setDmaapHost(String dmaapHost) {
142         this.dmaapHost = dmaapHost;
143     }
144
145     public void setDmaapPort(int dmaapPort) {
146         this.dmaapPort = dmaapPort;
147     }
148
149     public void setDmaapProtocol(String dmaapProtocol) {
150         this.dmaapProtocol = dmaapProtocol;
151     }
152
153     public void setDmaapUriPathPrefix(String dmaapUriPathPrefix) {
154         this.dmaapUriPathPrefix = dmaapUriPathPrefix;
155     }
156
157     public void setDmaapTopicName(String dmaapTopicName) {
158         this.dmaapTopicName = dmaapTopicName;
159     }
160
161     public void setConsumerId(String consumerId) {
162         this.consumerId = consumerId;
163     }
164
165     public void setConsumerGroup(String consumerGroup) {
166         this.consumerGroup = consumerGroup;
167     }
168
169     public void setDmaapClientDelayInSeconds(int dmaapClientDelayInSeconds) {
170         this.dmaapClientDelayInSeconds = dmaapClientDelayInSeconds;
171     }
172
173 }